Plot inside a loop in MATLAB

Solution 1:

Use DRAWNOW

a = [1:100];
for i=1:100,
 plot([1:i], a(1:i));
 drawnow
end

Alternatively, you may want to have a look at ANYMATE from the file exchange.

Solution 2:

Another way to do this if you just want to visualise it without saving the animation, is to use refreshdata instead of plot for subsequent plots. You will still need to call drawnow for it to update on-screen.

either use

set(fig_handle,'XData',new_xdata_array)
set(fig_handle,'YData',new_ydata_array)
refreshdata
drawnow

or use

set(fig_handle,'XDataSource',xdata_array)
set(fig_handle,'YDataSource',ydata_array)

%call this whenever xdata_array and ydata_array are assigned new values to see it updated in the plot
refreshdata
drawnow

for your example, this might look like:

a=[1:100];

figure;
h=plot(1,a(1));
for i=2:100
  set(h,'XData',[1:i])
  set(h,'YData',a(1:i))
  refreshdata
  drawnow
end

It's not all that useful for simple line plots (for which plot(); drawnow; is simpler and faster), but when you need to create more complicated figures involving multiple plot types, this can be useful.

Solution 3:

From the documentation for comet.m

t = 0:.01:2*pi;
x = cos(2*t).*(cos(t).^2);
y = sin(2*t).*(sin(t).^2);
comet(x,y);