How do I save values calculated from a while loop as a single 1D array
12 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Alex Owen
am 10 Dez. 2015
Beantwortet: Star Strider
am 10 Dez. 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 Kommentare
Akzeptierte Antwort
Star Strider
am 10 Dez. 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 Kommentare
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!