How can I create a loop to show a table with number of iterations and its roots in secant method?
1 view (last 30 days)
Show older comments
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
0 Comments
Accepted Answer
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
More Answers (0)
See Also
Categories
Find more on Get Started with MATLAB in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!