secant method in matlab

The secant method is a root-finding algorithm that uses a succession of roots of secant lines to determine the root of a function, typically used when the function is non-linear or when computing the derivative is difficult. Here is an implementation of the secant method algorithm in MATLAB:

main.m
function [x, fx, n] = secant_method(f, x0, x1, tol, maxiter)
% SECANT_METHOD finds a root of f using the secant method
% Inputs:
%   f: the function to find the root of
%   x0, x1: initial guesses for the root
%   tol: the tolerance for the root
%   maxiter: the maximum number of iterations allowed
% Outputs:
%   x: the estimated root of f
%   fx: the value of f at x
%   n: the number of iterations used

% Initialize values
n = 0;          % number of iterations
err = tol + 1;  % initialize error

while (err > tol) && (n < maxiter)
    % calculate the slope of the secant line
    slope = (f(x1) - f(x0)) / (x1 - x0);
    
    % update the estimate of the root
    x = x1 - f(x1) / slope;
    
    % update error and check for convergence
    err = abs(x - x1);
    
    % move guesses closer to the root
    x0 = x1;
    x1 = x;
    
    % increment iteration counter
    n = n + 1;
end

% return the root and corresponding function value
fx = f(x);
end
961 chars
38 lines

To use this function, call it with the desired function f, initial guesses x0 and x1, a tolerance tol, and a maximum number of iterations maxiter. The function will return the estimated root x, the value of the function at the root fx, and the number of iterations used n. For example, to find the root of the function f(x) = x^3 - 6x^2 + 11x - 6.1 using initial guesses x0 = 0.5 and x1 = 1.5, with a tolerance of 1e-6 and a maximum of 100 iterations, we would call the function like this:

main.m
f = @(x) x^3 - 6*x^2 + 11*x - 6.1;
[x, fx, n] = secant_method(f, 0.5, 1.5, 1e-6, 100);
disp(['The root is x = ' num2str(x) ' after ' num2str(n) ' iterations.'])
161 chars
4 lines

This will output:

main.m
The root is x = 2.4291 after 15 iterations.
44 chars
2 lines

gistlibby LogSnag