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');

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);

  %Or Plot something, then Add to Movie:
  f = getframe;

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


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

  • Pingback: Tool of the Week: Pretty(er) Matlab Plots | Mike Soltys()

  • Peter Polivka

    On a Mac (or PC) is there a way to write the movie as something other than a .avi file? Using either the method above or something similar to movie2avi()?

    • mrsoltys

      You could use '.mj2' instead of '.avi' in the code, keeping everything else the exact same. This will create a Motion JPEG 2000 movie instead of an Audio Video Interleave, however I've always been happy with the avi format. For more info, and to set options specific to each file type, see the VideoWriter class documentation.

  • Thank you! I always wanted to do this but never knew about VideoWriter before.

  • Adnan

    Nice 🙂

  • Jen

    Cool! Had you taught me this tool tip 4 years ago, I could have avoided the whole import-200-png-files-to-windows-moviemaker debacle. That makes it sound bad. It wasn't actually that hard. I also didn't know you 4 years ago.

  • Maziar

    Thanks Dude!

  • Bret

    There is a bug in getframe with Vista and Windows 7 that prevents this from working for surface plots made with pcolor and other functions. See for more details and two possible work arounds. The first work around, using "set(gcf, 'Renderer','zbuffer'), worked for me using Matlab R2012b under Windows 7 on a Dell T7500.

  • Fahrudin

    How do we make picture or plot our figure from movie?