From charlesreid1

This page will demonstrate how to create a movie from a set of Matlab plots. This will allow you to make some nice videos from Matlab plots.

Step 1: Generate Matlab Plots

Obviously you will have your own particular Matlab script generating your own plots. However, for the sake of illustration, I will use a sample script to illustrate the steps involved in creaing a Matlab video.

Sample Script

My sample script plots a sine wave for the domain with a time-varying phase shift.

MatlabVideoExample.png

The following Matlab script will generate the plot being visualized:

close all;

x=[0:(pi/16):2*pi];

y_0 = sin(x);

z=0;

for i=0:(pi/32):2*pi
    y_1 = sin(x-i);

    plot(x,y_0,'k-',x,y_1,'r--')

    xlabel('x ');
    ylabel('y(x)');
    axis([0 2*pi -1 1]);

    % Matlab commands to save plots
    %  to image files go here

    z = z + 1;
    pause(0.1);
end

The set of images of plots generated by this Matlab script can be downloaded here: http://files.charlesmartinreid.com/matlab_video_example.tar.gz

Unzip this to anywhere on your computer.


Step 2: Save Matlab Plots to Image Files

Once you have a script that will create the Matlab plots you want to make into a video, the next step is to tell Matlab to save each plot to an external image file. This can be accomplished using Matlab's saveas command (try help saveas).

In the above example, the following lines would be added:

    filename = sprintf('image_%0.4d.png',z);
    saveas(gcf,filename,'png');

which will create a set of 65 image files named file_0001.png through file_0064.png.

The sprintf command uses the syntax of printf (a C function, see [1]), but it prints the result to a string, rather than to output. The symbol %0.4d means "print a digit number, with a width of 4, and fill the width with zeros (so that 1 becomes 0001, 50 becomes 0050, etc.)

The saveas command is telling Matlab to save the plot to the file in png format.


Step 3: Postprocess Images

I don't have any specific examples here, but sometimes you need to postprocess your images, so this step would go here.


Step 4: Assemble Image Series into Video

This step requires Ffmpeg. The Ffmpeg page contains a section on converting images to video. This is the process that must be used to assemble the series of images into a video.

In the Matlab file, we gave sprintf the syntax %0.4f. This can also be used in calling ffmpeg (but without the dot between 0 and 4):

$ ffmpeg -i image_%04d.png -qscale 1 movie.mpg

Link to the final movie: click image below

MatlabVideoExample.png

For more options besides qscale, see Ffmpeg#Images_to_video.