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

1 vue (au cours des 30 derniers jours)
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

Réponse acceptée

Alan Stevens
Alan Stevens le 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

Plus de réponses (0)

Catégories

En savoir plus sur Get Started with MATLAB dans Help Center et File Exchange

Tags

Produits

Community Treasure Hunt

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

Start Hunting!

Translated by