How do I save values calculated from a while loop as a single 1D array

12 visualizaciones (últimos 30 días)
I have this while loop which works fine. I can display all of the values of e I want by using fprintf, but how do I store these values of e as a single 1D array?
function Newton
x = 4;
finalroot = 2.72;
diff = 1;
while diff > 0.5e-7
xlast = x;
x = xlast - f(xlast)/fd(xlast);
diff = abs(x - xlast);
e = abs(finalroot - x);
fprintf('%1.8f\n',e)
end
function y = f(x)
y = x.^3 - 2.44*x.^2 - 8.9216*x + 22.1952;
function z = fd(x)
z = 3*x.^2 - 4.88*x - 8.9216;
Really appreciate any help.

Respuesta aceptada

Star Strider
Star Strider el 10 de Dic. de 2015
You have to change your code to add a counter:
x = 4;
finalroot = 2.72;
diff = 1;
k1 = 1;
while diff > 0.5e-7
xlast = x;
x = xlast - f(xlast)/fd(xlast);
diff = abs(x - xlast);
e(k1) = abs(finalroot - x);
fprintf('%1.8f\n',e(k1))
k1 = k1 + 1;
end
The initial ‘k1’ assignment initialises the counter, then it is incremented after the ‘e(k1)’ assignment in every iteration of the loop. (It also keeps track of the number of iterations if you need to access that information.)

Más respuestas (0)

Categorías

Más información sobre Loops and Conditional Statements en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by