Animation process in Matlab

2019-08-26 19:58发布

问题:

I am just learning how to use Matlab. The problem is animating simple 2D plots. In trying to animate a line from (0,0) to (0, 10) connecting them in an animation I have this so far:

x = 0;
p = plot(x, y, 'o', 'EraseMode', 'none'); % p is the handle, for later manipulations
axis equal
for k = 0:1:10 % the idea here is to have k go from 0 to 10 and set y to that value
    y = k;
    set(p,'XData', x, 'YData', y) % then this adds another point based on that new y 
drawnow
end

The problem is, when this is run, is that it only plots the first point. Any help appreciated.

回答1:

You should draw a line define by two points, and then at each iteration update the y value of the second point:

h = plot([0 0],[0 0]); %// draw line initially
axis([-1 1 0 10]) %// freeze axis to see how the line grows
for k = 0:.1:10
    set(h,'YData',[0 k]) %// update second y value
    drawnow
end


回答2:

MATLAB introduced a new way of animating lines, starting with version R2014b, called animatedLine.

Here's how you can use it to draw the vertical line in your question.

x = 0;
h = animatedline();
set(gca,'ylim',[0 10],'xlim',[-5 5],'box','on');
for y=0:0.0001:10;
    addpoints(h,x,y);
    drawnow update
end

Adjust the step size (0.001 in this example) to increase or decrease your animation speed as necessary. To get a set frames per second you will want to look into a timer callback instead.