Creating Movies in MATLAB

Posted on at


This set of instructions detail how to create          movies in MATLAB 5.1, convert them to the standard movie format MPEG and how to play them. Limited knowledge of MATLAB or the MPEG format is assumed. This code has not been verified for any other MATLAB version. 

How to create MATLAB movies

1) Open MATLAB figure window:

>> fig1=figure(1);

2) Resize the figure window to size of movie required.

3) Record the size of the plot window:

>> winsize = get(fig1,'Position');

4) Adjust size of this window to include the whole figure window (if you require the axes, title and axis labels
     in the movie):

>> winsize(1:2) = [0 0];

5) Set the number of frames:

>> numframes=16;

6) Create the MATLAB movie matrix: 

>> A=moviein(numframes,fig1,winsize);

7) Fix the features of the plot window (ensures each frame of the movie is the same size):

>> set(fig1,'NextPlot','replacechildren')

8) Within a loop, plot each picture and save to MATLAB movie matrix:

>> for i=1:numframes
>>   plot(X(i),Y(i)); % plot command
>>   % add axis label, legends, titles, etc. in here
>>   A(:,i)=getframe(fig1,winsize);
>> end

This procedure creates a movie stored in a special format that is only readable in MATLAB. The first thing you will want to do is to play the movie:

>> movie(fig1,A,30,3,winsize)

where fig1 is the figure handle, A is the movie matrix, 30 is the number of times to repeat movie, 3 is the number of frames per second and winsize is the size of the movie window. You can also save this movie to a file to be loaded another time or on another machine running MATLAB:

>> save filename.mat A

and to reload:

>> load filename.mat

Unfortunately, the format in which MATLAB stores the movie is very wasteful of precious memory. Each time you save a frame of the movie, MATLAB creates a pixel map of the plot window and stores it in a column of the movie matrix. This is very wasteful as lots of pixels are likely to stay the same for large portions of the movie. It would be better to save the first frame (and possibly a few later on) and just record the changes in each subsequent frame. This is the idea behind the MPEG movie format.

The basic outline of the MPEG format is that at the start of each movie, and when the picture changes a lot (like when the scene changes in a real movie), a snapshot (pixel map) of the movie is taken. Then only the changes between each subsequent frame are saved. If the movie does not change much from the original picture then a huge amount of space can be saved. This type of movie format can be created in MATLAB using a free program called MPGWRITE available from the MATLAB website, discussed under Requirements below. 



About the author

160