How do I save values calculated from a while loop as a single 1D array
12 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Alex Owen
el 10 de Dic. de 2015
Respondida: Star Strider
el 10 de Dic. de 2015
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.
0 comentarios
Respuesta aceptada
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.)
0 comentarios
Más respuestas (0)
Ver también
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!