Search code examples
matlabanimationplotmatlab-figure

How to efficiently animate plots in MATLAB?


I wrote a simple code below for animating plots, but they tend to be rather computationally-intensive, taking entire seconds longer than intended:

function animplot(t,f,ymin,ymax,dt,num_iters)
h = plot(0,0); % set initial handle for first iteration
tic % start timer
for i=2:num_iters
    delete(h);
    h = plot(t,f(t-dt*i),'LineWidth',2,'color','b');
    axis([min(t) max(t) ymin ymax]); pause(1/num_iters)
end
toc % end timer, return time elapsed since 'tic'
end

Replacing 1/num_iters with dT = T / num_iters, and setting T = 1, computation time for 1000 iterations is 6+ secs (rather than 1). Sample animation for t = 0:.01:2*pi; f = @(t)sin(t); dt = .05; num_iters = 1000

Any more efficient methods of animating in this manner?


Solution

  • A significantly more efficient code, adapted per solution in related inquiry:

    function  animplot(t,f,ymin,ymax,dt,num_iters,T)
    % ANIMPLOT(t,f,ymin,ymax,dt,num_iters) -- f must be defined w/ handle, 
    % e.g. f = @(t)sin(t); default T = 5, num_iters = 500, dt = .05,
    % (ymax - ymin) = 1.4*range.
    switch nargin
        case 6; T = 5;
        case 5; T = 5; num_iters = 500;
        case 4; T = 5; num_iters = 500; dt = .05;
        case 2; T = 5; num_iters = 500; dt = .05; 
                ymin = 1.2*min(f(t)) - max(f(t))/5;
                ymax = 1.2*max(f(t)) - min(f(t))/5;
    end
    
    dT = T/num_iters; % set pause interval
    h = plot(0,0,'LineWidth',2,'color','b'); % set initial handle
    set(h, 'Xdata',t, 'Ydata', f(t));        % initialize curve plot
    axis([min(t) max(t) ymin ymax]);
    tic % start timer
    for i=2:num_iters
        pause(dT)
        set(h, 'Ydata', f(t-dt*i))
    end
    toc % end timer, return time elapsed since 'tic'
    end
    

    Note: num_iters serves primarily as animation 'resolution'; higher comes at expense of greater deviation from set T.