MATLAB animations

From Fluids Wiki
Jump to navigation Jump to search

There are many ways to generate animations of data from MATLAB. This page describes two relatively painless approaches.

Creating sequentially named frames

First you will need to create a bunch of frames in MATLAB and save them with sequential file names. For example if you are saving PNG files, you should have something like frame0001.png, frame0002.png, etc. Example MATLAB code to generate files follows:

figure(1); clf; set(gcf,'renderer','zbuffer');
for ii=1:10
  pcolor(randn(20));
  shading flat;
  filename=sprintf('frame%05d.png',ii);
  print('-dpng', '-r100', filename);
end


This is example code that generates random pictures. You can of course fine tune your frames. For example, set the size as described in MATLAB figures and specify what dpi to use, and hence control your frame size.

Option 1: Creating an AVI file

First create sequentially named PNG files, then run mkavi.sh in the directory with the PNG files. The code for mkavi.sh follows:

#!/bin/bash
# mkavi.sh - Create a DIVX movie from a bunch of PNG frames, store it in an AVI container.
#          - Requires mencoder.

# set frame rate
FPS=8
# set bitrate, larger = better quality but larger file
BITRATE=1000

# this should not be changed
THREADS=1
PASS=2

# Make an MPEG-4 file and put it in an AVI container for Windows playback
AVCOPTS="vcodec=mpeg4:vbitrate=$BITRATE:threads=$THREADS"
FOURCC=DIVX
if [ $PASS -eq 1 ]; then
  mencoder "mf://*.png" -mf fps=$FPS -o movie.avi -ovc lavc -ffourcc $FOURCC -lavcopts $AVCOPTS
else
  mencoder "mf://*.png" -mf fps=$FPS -o /dev/null -ovc lavc -ffourcc $FOURCC -lavcopts $AVCOPTS:vpass=1
  mencoder "mf://*.png" -mf fps=$FPS -o movie.avi -ovc lavc -ffourcc $FOURCC -lavcopts $AVCOPTS:vpass=2
  rm -f divx2pass.log
fi

Option 2: Creating an animated GIF file

First create sequentially named GIF files.

  • Someone complete this section