In: Computer Science
In MATLAB write a function secant.m to apply the secant method.
function [x,i] = secant(f, x0, x1, tol, maxiters)
[x,i] = secant(f, x0, x1, tol, maxiters) performs the secant method with f(x), starting at x_0 = x0 and x_1 = x1, and continuing until either |x_i+1 - x_i| <= tol, or maxiters iterations have been taken. The number of iterations, i, is also returned. An error is raised if the first input is not a function handle. A warning is raised if the maximum number of iterations is reached without achieving the tolerance.
Test the function on the problem f(x) = 0.9 cos(x) - sqrt(x) = 0, with starting values x0 = 0 and x1 - 1, and a tolerance of 10^-8 and maxiters of 20.
Hi,
Please find the matlab script below:
Matlab function
%%%%%%%%
function [x,i] = secant(f, x0, x1, tol, maxiters)
%Secant method
% [x,i] = SECANT(f, x0, x1, tol, maxiters)
% initialise iterate counter
counter = 0;
x_1 = x1;
x_0 = x0;
while( abs(x_1 - x_0) > tol && counter <
maxiters)
x_2 = x_1 - (f(x_1)*(x_1 - x_0))/(f(x_1) -
f(x_0));
x_0 = x_1;
x_1 = x_2;
counter = counter + 1; % increment counter by
one
end
i=counter;
x=x_1;
if (i > maxiters)
disp('Error : Max iterations reached.');
end
%%%%%%%%
Driver script with sample code for the given function:
%%%%%%%%
%Define the function
f = @(x) 0.9*cos(x) - sqrt(x);
%Set initial bounds
x0 = 0;
x1 = 1;
%set given tolerance
tol = 1e-8;
%set max iterations
maxiters = 20;
%Invoke the function
[x,i]=secant(f, x0, x1, tol, maxiters);
fprintf('x=%6.3f\n',x);
fprintf('i=%2d\n',i);
%%%%%%%%%
Screenshot
---------------------------------------------------------------------
Hope this helps.