dsax7
dsax7

Reputation: 1343

Animated plot in matlab

I am trying to create an animated plot of triangles and the end result should be ten triangles followed by two bigger triangles followed by a straight line. Using the matlab documentation, I ended up having this, which results an animated sin plot:

h = animatedline;
axis([0 4*pi -1 1])
x = linspace(0,4*pi,2000);

for k = 1:length(x)
    y = sin(x(k));
    addpoints(h,x(k),y);
    drawnow
end

The problem is that the plot is really slow and as soon as I changed y=sin(x(k)) to a triangular form, it got even worst. Is there a better way to do an animated plot or at least to adjust the speed? (if the speed is not dependant on the computer)

Upvotes: 3

Views: 553

Answers (2)

Luis Mendo
Luis Mendo

Reputation: 112659

You can speed it up a little by

  • Computing a y vector at once, instead of computing each value in the loop.
  • Updating the XData and YData properties of a plot, instead of using animatedline.

The code becomes:

h = plot(NaN,NaN);
axis([0 4*pi -1 1])
x = linspace(0,4*pi,2000);
y = sin(x);

for k = 1:length(x)
    set(h, 'XData', x(1:k), 'YData', y(1:k))
    drawnow
end

The gain in speed is small, though. If you need more speed you probably need to decrease the number of points.

Upvotes: 1

OmG
OmG

Reputation: 18838

You can examine comet function to animate the curve:

t = linspace(0,4*pi,2000);
comet(t, sin(t));

It would be smooth and easier to animate a curve (see its documentation). Also, for 3d curves you can use comet3.

Upvotes: 0

Related Questions