# trying to make a graph of each iteration in my while loop

3 views (last 30 days)
tyler hollings on 2 Oct 2020
Answered: Priysha LNU on 5 Oct 2020
i use a pause(0.5) to get a graph out which works however once i pause it pulls me out of the while loop
function [c]= bisection(a,A,B,varargin)
nvarargs =length(varargin);
if nvarargs>3
error('requires at most 3 optional inputs');
end
%set defaults for optional inputs
optargs = {0.000001 50 0};
optargs(1:nvarargs) = varargin;
[tol,maxiter,plt] = optargs{:};
if a(A)*a(B)>0
error('must choose new bracket')
end
i=0;
while i~=maxiter
i=i+1
c=(A+B)/2
if i>1
ea=abs(c-X);
if abs(a(c))<=tol | ea<= tol
i=maxiter;
elseif i==maxiter & (abs(a(c))>tol | ea >tol)
error('root within given tolerance not found within maxiterations')
end
end
% if i>1 & plt==1
% pause(0.5)
% x_ax=[A,B,c]
% Y_ax=[a(A),a(B),a(c)]
% plot(x_ax,Y_ax)
%
% end
if a(A)*a(c)<0
B=c;
else
A=c;
end
X=c;
a(c)
end
end
i commented the relevant bits of the function
per isakson on 2 Oct 2020
... and replacing
plot(x_ax,Y_ax) % plots to the current axes, i.e. overwrites
by
figure, plot(axes,x_ax,Y_ax) % creates a new figure for every plot
will give you a bunch of figures, each with one diagram

Priysha LNU on 5 Oct 2020
You may use saveas function in MATLAB to save plots in each iteration of the loop.
Example :
for k=1:5
h=figure
plot(...)
saveas(h,sprintf('FIG%d.png',k)); % will create FIG1, FIG2,...
end
DISCLAIMER: These are my own views and in no way depict those of MathWorks.