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

26 views (last 30 days)
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.

Accepted Answer

Star Strider
Star Strider on 10 Dec 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.)

More Answers (0)

Categories

Find more on Creating and Concatenating Matrices in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!