Tool of the Week: Making Animations in Matlab


Once you've made a pretty plot in Matlab, making an animation might help you understand temporal phenomena.  Making an animation is super easy in matlab, weither you're working with figures or images.  There are two methods to do this, but the most robust is using the VideoWriter class.  It's compatible with all versions of quicktime on both Mac and PC.  Here's how you do it:

1) Initialize your animation 

vidObj = VideoWriter('Movie.avi');
vidObj.FrameRate=23;
open(vidObj);

Note: I don't go below 23 Hz, or videos start to look choppy.

2) Do something in a loop, and add frames to your animation - there are 2 methods to do this.  If you're using images, use im2frame, otherwise if you want to get the current figure, use getframe.

for i=1:100
  %do something

  %add the image to your movie:
  f = im2frame(Img);
  writeVideo(aviobj,f);

  %Or Plot something, then Add to Movie:
  plot(x,y);
  f = getframe;
  writeVideo(vidObj,f);

Note: I prefer the im2frame option if at all possible for a lot of my work, although the getframe method is the only method that works for plots.

For the getframe method, it's important to note that while the loop is running, you can't open up other windows on top of the figure window that is making the movie, or they'll show up in your movie.  (E.g., don't start browsing the web while your figure is running, or all your web surfing will show up in your animation)

3) Close the animation

close(vidObj);

4) Enjoy! - the video will be saved in the working matlab directory