How to store iteration while loop result?

32 ビュー (過去 30 日間)
Yanuar Rizki Pahlevi
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 Center および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by