So here is the funciton that I created:
function S = Secant(po,p1)
f = @(x) -x^3-cos(x);
tol = 10^-7;
n=1;
p=[];
p(n-1)=po;
p(n-2)=p1;
n=n+1;
p(n)=p(n-1)-f(p(n-1).*(p(n-1)-p(n-2)))/f(p(n-1)-f(p(n-2)));
while abs(f(p(n)))>tol && abs(p(n)-p(n-1))>tol
n=n+1;
p(n)=p(n-1)-(f(p(n-1).*(p(n-1)-p(n-2)))/(f(p(n-1))-f(p(n-2))));
end
This error is showing up and I'm not sure what is wrong... Error in Secant (line 6) p(n-1)=po;
function p = Secant(po,p1)
f = @(x) -x^3-cos(x);
tol = 10^-7;
p(1)=po;
p(2)=p1;
n=3;
while abs(p(n-2)-p(n-1))>tol
p(n)=p(n-1)-f(p(n-1))*(p(n-1)-p(n-2))/(f(p(n-1))-f(p(n-2)));
n=n+1;
end
end
Save the above code as a function Secant.m then type S=Secant(-1,1) in the command window. You will get an entire iteration like this
S =
Columns 1 through 7
-1.0000 1.0000 -0.5403 -1.8228 -0.6684 -0.7510 -0.8930
Columns 8 through 12
-0.8622 -0.8654 -0.8655 -0.8655 -0.8655
The last number is your answer and you can see the convergence by plotting the values using the command plot(S) ! Substitute your answer -0.8655 in the function and you will get a number very close to zero. If you want to see more digits in the code type "format long" in the command line then run the code. If you want to see the number with less digits as previously type "format short". :There are many issues in your code many brackets were misplaced. You should learn MATLAB very seriously !