# Math Help - secant method

1. ## secant method

i have created this script file for fniding roots of x^3-x-3 using the secant method.

its not working,for me,juz wanted to know if something is wrong iwth the file. also how can i plot the root estimate along each iteration?
myintial estimate should be x0=0
here is my script file:

function [x]=sector(g,x0,x1,error,m)
x(1)=x0; x(2)=x1;
f(x(1))=feval(g,x0);
f(x(2))=feval(g,x1);
n=2;
for i=2:m
rfp=( x(i)-x(i-1) )/( f(x(i)) -f(x(i-1)) );
x(i+1)=x(i)-f(x(i))*rfp;
n=n+1
if abs(x(i+1)-x(i)) < error; break; end
end

>> g=@(x) x^3-x-3;
>> sector(g,0,2,1e-4,30)
??? Attempted to access f(0); index must be a positive integer or logical.

Error in ==> sector at 3
f(x(1))=feval(g,x0);

i dont know whts wrong with my script file. can anyone help me,also how wold i plot the root estimates along each iteration?

2. Originally Posted by mithilesh
i have created this script file for fniding roots of x^3-x-3 using the secant method.
The secant rule uses the itteration:

$x_{n+1}=x_n-\frac{x_n-x_{n-1}}{f(x_n)-f(x_{n-1})}f(x_n)$

to itterate its way to a solution of $f(x)=0$.

This is almost exactly the same as Newton-Raphson except the explicit derivative of $f(x)$ is replaced by an estimate derived from the last two itterates (or the two initial guesses at start up).

So the code for this is most easily obtained by modifying that for Newton-Raphson:

Code:
function rt=SCNTroot(f,x0,x1,tol)
%================================================
% f the function we wish to find the root of (function handle)
% x0 and x1 two distinct initial guesses at the root
% tol stopping tolerance
%================================================
xx1=x0;xx2=x1;
err=1e6;
while err>tol
fxx1=feval(f,xx1);
fxx2=feval(f,xx2)

xnew=xx2-(xx2-xx1)/(ffx2-fxx1)*fxx2;
err=abs(xnew-xx);
xx1=xx2;xx2=xnew
end
rt=xx2;
If we also wish to return a vector of the itterates we can modify this to:

Code:
function [rt,Vrt]=SCNTroot(f,x0,x1,tol)
%================================================
% f the function we wish to find the root of (function handle)
% x0 and x1 two distinct initial guesses at the root
% tol stopping tolerance
%================================================
xx1=x0;xx2=x1;
Vrt=[x0,x1];
err=1e6;
while err>tol
fxx1=feval(f,xx1);
fxx2=feval(f,xx2)

xnew=xx2-(xx2-xx1)/(ffx2-fxx1)*fxx2;
err=abs(xnew-xx);
xx1=xx2;xx2=xnew
end
rt=xx2;
Vrt=[Vrt,rt];
(note I have not tested this so there may be residual bugs)