17

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?

4 Answers 4

22

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.

Sign up to request clarification or add additional context in comments.

1 Comment

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.
6

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.

Comments

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

Comments

0

Matlab allows you to sort-of automate a loop statement for variables

x = 0.0:0.1:2*pi

plot(x,cos(x));

is an example......

A lot of times you don't really need to plot 'in' a loop

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.