Reputation: 19
So I'm trying to code a function that will implement the secant method to a function(f) that will be input by the user and add the result of each iteration to the vector. I get an error stating that x is undefined which is understandable, but I'm unsure of how to define it. I'm trying to write it in a way where the argument f can be a function in terms of x, eg. x^3 +12, as opposed to the name of a seperate function file.
function [xans, xi, iter] = secant( f, x0, x1, tol )
k = 1;
a = x0;
b = x1;
c = f(b)*((b-a)/(f(b)-f(a)));
while abs(c) >= tol
xi(k) = b-c;
a = b
b = xi(k)
k = k+1;
end
disp(x)
disp(xi)
disp(iter)
Upvotes: 1
Views: 203
Reputation: 38032
Use a function_handle
:
[xans,xi,k] = secant(@myFunc,1,2,0.0001);
Also, call the funciton inside the loop, otherwise, it doesn't update:
function [xans, xi, k] = secant(f, x0, x1, tol)
%// etc.
while abs(c) >= tol
c = f(b) * (b-a)/(f(b)-f(a));
%// etc.
end
end
Upvotes: 0
Reputation: 47392
You seem a little confused about loops and functions in Matlab. The function you have written doesn't do any updating of the variables inside the loop. When you write
c = f(b) * (b-a) / (f(b) - f(a));
that stores one value in c
, but it doesn't automatically update c
every time you go through the loop. Instead, I'd write something like this
function x1 = secant(f, x0, x1, tol)
y1 = f(x1);
y0 = f(x0);
while abs(y1) > tol
tmp = x1; %// Store the old value of x1
x1 = x1 - y1 * (x1 - x0) / (y1 - y0); %// Use the secant method to update x1
x0 = tmp; %// x0 gets the old value of x1
y0 = y1; %// We already know what f(x0) is
y1 = f(x1); %// Need to re-compute f(x1)
end
which you can then call as follows. The first argument is known as a function handle.
>> secant( @(x)x^2-2, 0, 1, 1e-6)
ans =
1.414213562057320
Upvotes: 2