Macarse
Macarse

Reputation: 93143

Plot inside a loop in MATLAB

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?

Upvotes: 17

Views: 84288

Answers (4)

Observer Space
Observer Space

Reputation: 1

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

Upvotes: 0

MatlabDoug
MatlabDoug

Reputation: 5714

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

Upvotes: 3

JS Ng
JS Ng

Reputation: 725

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.

Upvotes: 6

Jonas
Jonas

Reputation: 74940

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.

Upvotes: 22

Related Questions