Plot inside a loop in MATLAB

后端 未结 4 1669
遇见更好的自我
遇见更好的自我 2020-12-01 08:41

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 loo

相关标签:
4条回答
  • 2020-12-01 08:54

    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.

    0 讨论(0)
  • 2020-12-01 08:58

    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

    0 讨论(0)
  • 2020-12-01 08:59

    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);
    
    0 讨论(0)
  • 2020-12-01 09:05

    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.

    0 讨论(0)
提交回复
热议问题