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

1 visualización (últimos 30 días)
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

Respuesta aceptada

Alan Stevens
Alan Stevens el 12 de Oct. de 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

Más respuestas (0)

Categorías

Más información sobre Get Started with MATLAB en Help Center y File Exchange.

Etiquetas

Productos

Community Treasure Hunt

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

Start Hunting!

Translated by