How can I create a loop to show a table with number of iterations and its roots in secant method?

2 views (last 30 days)
I tried modifying the for loop command to create iterations but as soon as I run it, the code doesn't show any list of iterations and its roots. Can someone help me how can I show a table like list of iterations and roots of the function with this code?
My code only shows the root and how many iteration it used
clc
f=@(x) e^(0.5*x)+(5*x);
x(1)=0.8;
x(2)=0.7;
tol=0.002;
i=0;
iteration=0;
for i=3:1000
x(i) = x(i-1) - (f(x(i-1)))*((x(i-1) - x(i-2))/(f(x(i-1)) - f(x(i-2))));
a_e = abs((x(i)-x(i-1))/x(i))*100;
iteration=iteration+1;
if a_e<tol
root=x(i)
iteration=iteration
break
fprintf('%d %d %d\tol', i, x(i), a_e)
end
end

Accepted Answer

Alan Stevens
Alan Stevens on 12 Oct 2022
Possibly like this (though using a while loop would be better):
f=@(x) exp(0.5*x)+(5*x);
x(1)=0.8;
x(2)=0.7;
tol=0.0001;
for i=3:1000
x(i) = x(i-1) - (f(x(i-1)))*((x(i-1) - x(i-2))/(f(x(i-1)) - f(x(i-2))));
a_e = abs((x(i)-x(i-1))/x(i))*100;
iteration(i-2)=i-2;
if a_e<tol
root=x(i);
break
end
fprintf('%d %f %f \n', i-2, x(i), a_e)
end
1 -0.158840 540.695015 2 -0.182052 12.750391 3 -0.182553 0.274115 4 -0.182553 0.000136

More Answers (0)

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Tags

Products

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!