Animation in MATLAB

Kate picture Kate · Apr 26, 2010 · Viewed 9.5k times · Source

How do I animate a surface if it's coordinates change in time (e.g. ellipsoid) using MATLAB?

Answer

gnovice picture gnovice · Apr 26, 2010

Here are a couple of examples of ways you can animate plots in MATLAB...

Modify a plot in a for loop:

You can create a loop in which you change the surface coordinates, update the plot object using the set command, and use the pause command to pause each loop iteration for a short period of time. Here's an example:

[x, y, z] = ellipsoid(0, 0, 0, 4, 1, 1);  % Make an ellipsoid shape
hMesh = mesh(x, y, z);                    % Plot the shape as a mesh
axis equal                                % Change the axis scaling
for longAxis = 4:-0.1:1
  [x, y, z] = ellipsoid(0, 0, 0, longAxis, 1, 1);  % Make a new ellipsoid
  set(hMesh, 'XData', x, 'YData', y, 'ZData', z);  % Update the mesh data
  pause(0.25);                                     % Pause for 1/4 second
end

When you run the above, you should see the long axis of the ellipsoid shrink until it is a sphere.


Modify a plot with a timer:

You can also use a timer object instead of a loop to execute the updates to the plot. In this example, I'll first make a function timer_fcn that I want executed each time the timer fires:

function timer_fcn(obj,event,hMesh)
  n = get(obj, 'TasksExecuted');  % The number of times the
                                  %   timer has fired already
  [x, y, z] = ellipsoid(0, 0, 0, 4-(3*n/40), 1, 1);  % Make a new ellipsoid
  set(hMesh, 'XData', x, 'YData', y, 'ZData', z);    % Update the mesh data
  drawnow;                                           % Force the display to update
end

Now I can create the plot and timer and start the timer as follows:

[x, y, z] = ellipsoid(0, 0, 0, 4, 1, 1);  % Make an ellipsoid shape
hMesh = mesh(x, y, z);                    % Plot the shape as a mesh
axis equal                                % Change the axis scaling
animationTimer = timer('ExecutionMode', 'fixedRate', ...  % Fire at a fixed rate
                       'Period', 0.25, ...                %   every 0.25 seconds
                       'TasksToExecute', 40, ...          %   for 40 times and
                       'TimerFcn', {@timer_fcn, hMesh});  %   run this function
start(animationTimer);  % Start timer, which runs on its own until it ends

This will display the same animation as the for-loop example. And once you're done with the timer object, remember to always delete it:

delete(animationTimer);