How to store iteration while loop result?
15 views (last 30 days)
Show older comments
Yanuar Rizki Pahlevi
on 8 Sep 2020
Commented: Yanuar Rizki Pahlevi
on 8 Sep 2020
Hi guys, I need help.
how can I store iteration result?
while abs(xj-x0)>=error
disp('*****************')
x0=xj %new value of x0 to generate new xj in next iteration
y=subs(poly2sym(f),x,x0);
fx=[y]
Upper=subs(poly2sym(firstDiff),x,x0);
Lower=subs(poly2sym(secondDiff),x,x0);
xj=x0-(Upper/Lower)
I need to store two vectors, because I will create a plot using these two vector as input
- vector of x0 values
- vector of fx values
0 Comments
Accepted Answer
Walter Roberson
on 8 Sep 2020
all_x0 = x0;
all_fx = fx; %you should check that I used the right variable
counter = 1;
while abs(xj-x0)>=error
disp('*****************')
x0=xj %new value of x0 to generate new xj in next iteration
y=subs(poly2sym(f),x,x0);
fx=[y]
counter = counter + 1;
all_x0(counter) = x0;
all_fx(counter) = fx;
Upper=subs(poly2sym(firstDiff),x,x0);
Lower=subs(poly2sym(secondDiff),x,x0);
xj=x0-(Upper/Lower)
end
More Answers (1)
Dana
on 8 Sep 2020
If you only expect a relatively small number of iterations to occur, then the following will work fine:
x0sv = [];
fxsv = [];
while abs(xj-x0)>=error
disp('*****************')
x0=xj %new value of x0 to generate new xj in next iteration
y=subs(poly2sym(f),x,x0);
fx=[y]
Upper=subs(poly2sym(firstDiff),x,x0);
Lower=subs(poly2sym(secondDiff),x,x0);
xj=x0-(Upper/Lower)
x0sv = [x0sv;x0];
fxsv = [fxsv;fx];
end
For a large numbers of iterations this isn't ideal, since x0sv and fxsv are expanding size on each iteration, and that's a slow step to implement. A better option would be to pre-allocate arrays based on an upper-bound estimate for the number of iterations, and then add a new chunk if you run out of room. Something like, for example:
nmax = 1000; % initial guess for max number of iterations
x0sv = zeros(nmax,1);
fxsv = zeros(nmax,1);
n = nmax; % variable to track current size of x0sv, fxsv
j = 0;
while abs(xj-x0)>=error
j = j+1; % counter to keep track of iteration number
disp('*****************')
x0=xj %new value of x0 to generate new xj in next iteration
y=subs(poly2sym(f),x,x0);
fx=[y]
Upper=subs(poly2sym(firstDiff),x,x0);
Lower=subs(poly2sym(secondDiff),x,x0);
xj=x0-(Upper/Lower)
if j > n % if current iteration > size of arrays
% expand arrays by another nmax elements each
x0sv = [x0sv;zeros(nmax,1)];
fxsv = [fxsv;zeros(nmax,1)];
n = n+nmax; % update size of arrays
end
x0sv(j) = x0;
fxsv(j) = fx;
end
0 Comments
See Also
Categories
Find more on Particle & Nuclear Physics 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!