MATLAB – how to make a movie of plots

Making a video of your moving graphs/charts is surprisingly easy to do in MATLAB. However most of my online searches gave me old outdated methods to do it. Here’s how to make a movie or a video in MATLAB.

I kept getting this freakin’ error using the old methods (i.e. the avifile() function):
“Windows Media Player cannot play the file. The Player might not support the file type or might not support the codec that was used to compress the file.”

So I found MATLAB recommends you use the VideoWriter() class…
http://www.mathworks.com/help/techdoc/ref/videowriterclass.html

They have a nice little example in the documentation, but for the impatient, here’s my quick and dirty implementation of it (with some modifications/additions of course).

%% Movie Test.
 
%% Set up some function. 
% Sine between -2*pi and 2*pi.
x = (10*-pi:0.1:10*pi)'; % Note the transpose.
y = sin(x);
fid = figure;
hold on
% The final plot.
plot(x,y, '*');
 
%% Set up the movie.
writerObj = VideoWriter('out.avi'); % Name it.
writerObj.FrameRate = 60; % How many frames per second.
open(writerObj); 
 
for i=1:size(y)      
    % We just use pause but pretend you have some really complicated thing here...
    pause(0.1);
    figure(fId); % Makes sure you use your desired frame.
    plot(x(i),y(i),'or');
 
    %if mod(i,4)==0, % Uncomment to take 1 out of every 4 frames.
        frame = getframe(gcf); % 'gcf' can handle if you zoom in to take a movie.
        writeVideo(writerObj, frame);
    %end
 
end
hold off
close(writerObj); % Saves the movie.

Boom. There you go. You can now make a video of your complicated function for all to see. It’s that easy.

2 thoughts on “MATLAB – how to make a movie of plots”

Questions/comments? If you just want to say thanks, consider sharing this article or following me on Twitter!