# Secant Method – Matlab Script

This is a discription and explanation of the secant methid uses matlab to show the step by step iteration that are done to calculate the end value.

Using the following script, it produces a straight forward answer as to what the answer is by using the secant methid.

function x = secant(f_str, x0, x1, n)
% SECANT  Secant method
% X = SECANT(F_STR, X0, X1, N) performs N iterations of the secant method
% on the function f, starting with the initial iterates X0 and X1, where
% F_STR is the string representation of f.

f = inline(f_str);

xp = x0;
fp = f(xp);
x = x1;
fx = f(x);

for i = 1:n
xn = x – fx * (x – xp) / (fx – fp)
xp = x;
fp = fx;
x = xn;
fx = f(x);
end

However if you would like to see the step by step done behind the scenes of the secant method, use the following script.

function x = secant(f_str, x0, x1, n)
% SECANT Secant method
% X = SECANT(F_STR, X0, X1, N) performs N iterations of the secant method
% on the function f, starting with the initial iterates X0 and X1, where
% F_STR is the string representation of f.
% in the form f(x) = 0

f = inline(f_str);
a = x0;
b = x1;

disp(‘Number of Iterations =’)
disp(0)

disp(‘Xn =’)
disp(a)
disp(‘f(Xn) =’)
disp(f(a))

disp(‘Number of Iterations =’)
disp(1)

disp(‘Xn =’)
disp(b)
disp(‘f(Xn) =’)
disp(f(b))

for i = (1:n-1)
x = b – (f(b) * ((b-a)/(f(b)-f(a))));
if b == x
disp(‘This is the Highest Accuracy Achievable’)
i = i-1;
break
end
a = b;
b = x;

disp(‘Number of Iterations =’)
disp(i+1)
disp(‘Xn =’)
disp(x)
disp(‘f(Xn) =’)
disp(f(x))
end
disp(‘Number of Iterations Done:’)
disp(i+1)
end

The secant method is based off Newtons method which uses the differential of the function to closly approximate the answer, where by the more iterations, the closer the answer becomes. In stead of the differential, uses a tangent or secant line to approximate it. The accuraccy of answer increases by a factor of 1.618, meaning each iteration increases the decimal place accuracy by 1.618 places each time.

Other Iterative and Mathematical Method using Matlab and also other Mathematical Examples:

>>> Romberg Numerical Integration – Matlab Script

>>> Simpson’s Rule and Trapezoidal Rule of Numerical Integration – Matlab Scripts

>>> Newtons Method of finding Roots – Matlab Script

>>> Bisection Method of finding Roots – Matlab Script

Other Articles I have writen include:

>>> How to Build a Computer

>>> Restore to Factory Settings with Recovery Partition

>>> how to fix usbhub.sys blue screen error crashes

Share.