How to store iteration while loop result?

36 views (last 30 days)
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
  1. vector of x0 values
  2. vector of fx values

Accepted Answer

Walter Roberson
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
  1 Comment
Yanuar Rizki Pahlevi
Yanuar Rizki Pahlevi on 8 Sep 2020
hi, thanks for the solution.
but now the data cannot be plot because it says its not numeric

Sign in to comment.

More Answers (1)

Dana
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

Community Treasure Hunt

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

Start Hunting!