views:

839

answers:

3

I am doing something like this:

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

My issue is that the plot is not shown until the loop is finished. How can I show/update the plot in every iteration?

+6  A: 

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.

Jonas
While drawnow is the correct answer, I think one can also add a pause(eps) statement in the code in the place of drawnow. When matlab does the pause, even if only for this nano-fraction of a time slice, it also does a refresh on the figure.
woodchips
+3  A: 

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.

JS Ng
+1  A: 

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);
MatlabDoug

related questions