Matlab Animation

There are 2 basic methods of creating an animation in Matlab (plus the comet routine, which is limited to plotting one line):

Method 1: Movie-making Frame by Frame

The idea underlying this methoe is that a number of figures are created and each one is stored as a frame, using the getframe command. The movie is then played back on the screen with the movie command. This type of movie is ideal for color-filled contours and 3-dimensional surface animations.

You may download the sstmovie.m program file plus the data files (zipped). (Alternate method using pcolor instead of contour can be downloaded here).

Here's the code for that example:

% Load in monthly coads climatology and display as a movie
% written  for oc3030

reruns=1;                  % number of times movie is to play
fps=5;                     % frames per second

nframes = 12;              % number of frames in the movie
Frames = moviein(nframes); % initialize the matrix 'Frames'

title('SST Climatology')    

% Load each month, contour it and save it in a frame:
   load sstjan.dat
   contourf(sstjan); 
   colormap('jet')
   Frames(:,1)=getframe;
%
   load sstfeb.dat
   contourf(sstfeb);
   Frames(:,2) = getframe;
%
   ...

   ... do all 12 months that way, ending with:
   Frames(:,12) = getframe;

% Now play the movie: 
   movie(Frames,reruns,fps)

Saving your movie in mpeg format for the Web:

A simple call to the function "mpgwrite" after the movie function will save your movie as an mpeg file. The mpgwrite is downloadable from the Matlab website.

% Now save the movie as an mpeg file for use on the Web:
%map=colormap    % Uses the previously defined colormap 
%mpgwrite(Frames,map,'sstmovie.mpg')

Play this movie on the web

Method 2: Using Handle Graphics

This method is useful for line animations, where most of the plot remains the same, such as trajectories, time series, etc. The object is plotted and saved as a handle. Then this handle is used to change the properties of the object, like 'xdata' and 'ydata'. The object is replotted and the original object can either be erased or remain on the plot. This is done by the property 'erasemode': use 'xor' to erase previously plotted data and 'none' to keep previously plotted data. Other properties that can be set and changed are 'color', 'linestyle', and 'markersize'.

Example 1: Inertial motion demo:

Inertial motion is studied in the OC3240 Ocean Dynamics class, and this program illustrates the motion of a water particle under several scenarios.

Download the inert2.mat mat-file. Mouse the following commands into your matlab window. There are five different cases corresponding to five different trajectories. Each is plotted one step at at time, and the previous values are not erased. This is a good method for animating trajectories or time series.


% inertial.m: Animates trajectories for 5 cases demonstrating
%             inertial motion.  Here are the cases:
%             1. basic case:  wind stress in x and y directions  cyan
%                 of .1 Nm^-2, f=1x10^-4 s^-1, linear friction,
%                 mixed layer depth h=20m, no initial velocity.
%             2. Same as case 1, but no friction.                yellow
%             3. No wind forcing.  Water is given an initial     green
%                velocity of 10 cm/s. 
%             4. Wind is turned off after 2 days.                red 
%             5. Mixed layer depth is doubled (h=40m).           blue    

% Load all the variables which have been 'saved' as a .mat file:
load inert2.mat

% Set the starting point (x1,y1) (same as (0,0)) for each trajectory:
hstart1=line(x1(1),y1(1),'color','c','erase','none','linewidth',3);
hstart2=line(xr0(1),yr0(1),'color','y','erase','none');
hstart3=line(xnowind(1),ynowind(1),'color','g','erase','none');
hstart4=line(xrelax(1),yrelax(1),'color','r','erase','none');
hstart5=line(xdeep(1),ydeep(1),'color','b','erase','none');

% label axes, etc.
axis([-1000 25000 -25000 1000]); axis('equal') 
xlabel('x (m)')
ylabel('y (m)')
title('Inertial Motion Trajectories') 

% Loop through each trajectory, changing the data points.
for k=1:length(xdeep),
  set(hstart1,'xdata',x1(k),'ydata',y1(k));
  set(hstart2,'xdata',xr0(k),'ydata',yr0(k));
  set(hstart3,'xdata',xnowind(k),'ydata',ynowind(k));
  set(hstart4,'xdata',xrelax(k),'ydata',yrelax(k));
  set(hstart5,'xdata',xdeep(k),'ydata',ydeep(k));
  drawnow
end
axis([-1000 25000 -25000 1000]); axis('equal') 
Example 2: BT (Bathythermograph) Profiles

Download the p66.dat data file and the BT header file to run this program.

Copy and paste the following code into matlab. This example is similar to the inertial motion example, except that each profile is drawn and then erased and replaced by the next profile. An entire year of bathythermograph (BT) profiles from Ocean Station Papa in the North Pacific (50N, 145W) are animated.

  
% Sample of animation:  BT profiles for all of 1966 at
% Ship Papa (50N)  Show upper 200 m only.
% This version uses handle graphics to control the plot.

load p66.dat
nprofiles =2206;
z=1:5:200;          
p200=p66(:,1:40);        % Load upper 200m of profile
clear p66
load bt66.dat    
month=bt66(:,2);
day = bt66(:,3);
clear bt66
%
% Plot first profile and give it a handle:
h1=plot(p200(1,:),z,'erasemode','xor')
xlabel('Temperature (C)')
ylabel('Depth (m)')
title('Observed BT''s at OWS Papa - 1966')
axis([2 14 0 200]);axis('ij')

% Now plot the rest of the profiles:
for i=2:nprofiles,
  tz=p200(i,:);
  set(h1,'xdata',tz,'ydata',z);   %change data given to handle h1

drawnow
i   % Display number of the profile in the matlab window

% The plot may (or may not) go too fast!  Remove the comments from the     
% for loop below to slow it down...
% for j=1:100,
%    x(j) =  j* exp(pi);  
% end
 
end

Play this quicktime movie.


Please send all comments and suggestions for this course to the instructor: Arlene Guest: aguest@nps.edu

Last modified 27 August 2004

Disclaimer