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

12 次查看(过去 30 天)
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.

采纳的回答

Star Strider
Star Strider 2015-12-10
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 个)

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by