How to store iteration while loop result?

조회 수: 28 (최근 30일)
Yanuar Rizki Pahlevi
Yanuar Rizki Pahlevi 2020년 9월 8일
댓글: Yanuar Rizki Pahlevi 2020년 9월 8일
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

채택된 답변

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

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Dana
Dana 2020년 9월 8일
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

카테고리

Help CenterFile Exchange에서 Axis Labels에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by