MATLAB Language Fast drawing


Example

There are three main ways to do sequential plot or animations: plot(x,y), set(h , 'XData' , y, 'YData' , y) and animatedline. If you want your animation to be smooth, you need efficient drawing, and the three methods are not equivalent.

% Plot a sin with increasing phase shift in 500 steps
x = linspace(0 , 2*pi , 100);

figure
tic
for thetha = linspace(0 , 10*pi , 500)
    y = sin(x + thetha);
    plot(x,y)
    drawnow
end
toc

I get 5.278172 seconds. The plot function basically deletes and recreates the line object each time. A more efficient way to update a plot is to use the XData and YData properties of the Line object.

tic
h = [];   % Handle of line object
for thetha = linspace(0 , 10*pi , 500)
    y = sin(x + thetha);
    
    if isempty(h)
        % If Line still does not exist, create it
        h = plot(x,y);
    else
        % If Line exists, update it
        set(h , 'YData' , y)
    end
    drawnow
end
toc

Now I get 2.741996 seconds, much better!

animatedline is a relatively new function, introduced in 2014b. Let's see how it fares:

tic
h = animatedline;
for thetha = linspace(0 , 10*pi , 500)
    y = sin(x + thetha);
    clearpoints(h)
    addpoints(h , x , y)
    drawnow
end
toc

3.360569 seconds, not as good as updating an existing plot, but still better than plot(x,y).

Of course, if you have to plot a single line, like in this example, the three methods are almost equivalent and give smooth animations. But if you have more complex plots, updating existing Line objects will make a difference.