How to store iteration while loop result?
16 次查看(过去 30 天)
显示 更早的评论
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 个评论
采纳的回答
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 个)
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
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Axis Labels 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!