Animation

Ways to Animate Plots

You can create animated sequences with MATLAB® graphics in three different ways:

Movies are better suited to situations where each frame is fairly complex and cannot be redrawn rapidly. You create each movie frame in advance so the original drawing time is not important during playback, which is just a matter of blitting the frame to the screen. A movie is not rendered in real time; it is simply a playback of previously rendered frames.

The second technique, drawing, erasing, and then redrawing, makes use of different drawing modes supported by MATLAB graphics. These modes allow faster redrawing at the expense of some rendering accuracy, so you must consider which mode to select.

The third approach allows plots to be updated in data driven fashion and handles redrawing plots (if drawnow is called appropriately).

This section provides an example of each technique. To see more sophisticated demonstrations of these features, type demo at the MATLAB prompt and explore the animation demonstrations.

Movies

You can save any sequence of graphs and then play the sequence back in a short movie. There are two steps to this process:

Typically, you use getframe in a for loop to assemble the array of movie frames. getframe returns a structure having the following fields:

See image for more information on images.

Example — Visualizing an FFT as a Movie

This example illustrates the use of movies to visualize the quantity fft(eye(n)), which is a complex n-by-n matrix whose elements are various powers of the nth root of unity, exp(i*2*pi/n).

Creating the Movie

Create the movie in a for loop calling getframe to capture the graph. Since the plot command resets the axes properties, call axis equal within the loop before getframe.

for k = 1:16
	plot(fft(eye(k+16)))
	axis equal
	M(k) = getframe;
end

Running the Movie

After generating the movie, you can play it back any number of times. To play it back 30 times, type

movie(M,30)

You can readily generate and smoothly play back movies with a few dozen frames on most computers. Longer movies require large amounts of primary memory or a very effective virtual memory system.

Movies that Include the Entire Figure

If you want to capture the contents of the entire figure window (for example, to include GUI components in the movie), specify the figure's handle as an argument to the getframe command. For example, suppose you want to add a slider to indicate the value of k in the previous example.

h = uicontrol('style','slider','position',...
	[10 50 20 300],'Min',1,'Max',16,'Value',1)
for k = 1:16
	plot(fft(eye(k+16)))
	axis equal
	set(h,'Value',k)
	M(k) = getframe(gcf);
end

In this example, the movie frame contains the entire figure. To play so that it looks like the original figure, make the playback axes fill the figure window.

clf
axes('Position',[0 0 1 1])
movie(M,30)

Erase Modes

You can select the method used to redraw graphics objects. One event that causes an object to redraw is changing the properties of that object. You can take advantage of this behavior to create animated sequences. A typical scenario is to draw a graphics object, then change its position by respecifying the x-, y,- and z-coordinate data by a small amount with each pass through a loop.

You can create different effects by selecting different erase modes. This section illustrates how to use the three modes that are useful for dynamic redrawing:

All three modes are faster (albeit less accurate) than the normal mode used by MATLAB.

Example — Animating with Erase Modes

It is often interesting and informative to see 3-D trajectories develop in time. This example involves chaotic motion described by a nonlinear differential equation known as the Lorenz strange attractor. It can be written

in the form

with a vector-valued function y(t) and a matrix A that depends upon y.

The solution orbits about two different attractive points without settling into a steady orbit about either. This example approximates the solution with the simplest possible numerical method — Euler's method with fixed step size. The result is not very accurate, but it has the same qualitative behavior as other methods.

A = [ -8/3 0 0; 0 -10 10; 0 28 -1 ];
y = [35 -10 -7]';
h = 0.01;
p = plot3(y(1),y(2),y(3),'.', ...
    'EraseMode','none','MarkerSize',5); % Set EraseMode to none
axis([0 50 -25 25 -25 25])
hold on
for i=1:4000
    A(1,3) = y(2);
    A(3,1) = -y(2);
    ydot = A*y;
    y = y + h*ydot;
	% Change coordinates
    set(p,'XData',y(1),'YData',y(2),'ZData',y(3)) 
    drawnow
end

The plot3 statement sets EraseMode to none, indicating that the points already plotted should not be erased when the plot is redrawn. In addition, the handle of the plot object is saved. Within the for loop, a set statement references the plot object and changes its internally stored coordinates for the new location. While this manual cannot show the dynamically evolving output, this picture shows a snapshot.

Effectively, the graph created by this example contains only one dot. What you see on the screen are remnants of previous plots that MATLAB has been instructed not to erase. The only way to print this graph is with a screen capture.

Background Erase Mode.   To see the effect of EraseMode background, add these statements to the previous program.

p = plot3(y(1),y(2),y(3),'square', ...
    'EraseMode','background','MarkerSize',10,...
    'MarkerEdgeColor',[1 .7 .7],'MarkerFaceColor',[1 .7 .7]);

for i=1:4000
    A(1,3) = y(2);
    A(3,1) = -y(2);
    ydot = A*y;
    y = y + h*ydot;
    set(p,'XData',y(1),'YData',y(2),'ZData',y(3))
    drawnow 
end
hold off

Since hold is still on, this code erases the previously created graph by setting the EraseMode property to background and changing the marker to a "pink eraser" (a square marker colored pink).

Xor Erase Mode.   If you change the EraseMode of the first plot3 statement from none to xor, you will see a moving dot (Marker '.') only. Xor mode is used to create animations where you do not want to leave remnants of previous graphics on the screen. However, you should not rely on Xor mode to work properly in all situations. Some platforms and graphics subsystems do not support it and where it does work, performance can be much slower compared to other erase modes or animation methods.

Additional Examples

The MATLAB demo lorenz provides a more accurate numerical approximation and a more elaborate display of the Lorenz strange attractor example. Other MATLAB demos illustrate animation techniques.

Updating Plot Object Axis and Color Data

When you create a graph ,the MATLAB figure stores copies of

If the variables that these values represent are removed or changed, the copies of them in plot object are unaffected. However, you can update these copies (the properties XData, YData, ZData, and CData) at any time; when you do, the graph changes to reflect the updates.

Consequently, you can animate graphs by changing axis data. You can do one of the following:

Here obj_handle is a handle to the plot object you want to update or animate. All graph objects have data source properties (at least an XDatasource and a YDatasource; some also have a ZDatasource and a CDatasource) that by default are empty (axis data has no connection to workspace variables).

You make a persistent connection between axis data and a variable using set, as described above and illustrated by the following example. When refreshdata is called, the axis data is replaced by workspace data and the graph is redrawn.

Calling refreshdata only causes a graph to be redrawn if any of its declared data sources have changed. It updates all axes at the same time, and updates selected plot objects, and does so from a calling function's workspace or the base workspace.

As an example, this script calls refreshdata to animate an area graph of the Pythagorean theorem:

c = -pi:.04:pi;
cx = cos(c);
cy = -sin(c);
figure('color','white');
axis off, axis equal
line(cx, cy, 'color', [.4 .4 .8],'LineWidth',3);
title('See Pythagoras Run!','Color',[.6 0 0])
hold on
x = [-1 0 1 -1];
y =   [0 0 0 0];
ht = area(x,y,'facecolor',[.6 0 0])
set(ht,'XDataSource','x')
set(ht,'YDataSource','y')
for j = 1:length(c)
    x(2) = cx(j);
    y(2) = cy(j);
    refreshdata
    drawnow
end

The script needs drawnow to display the results at each iteration. When you call refreshdata from the command line or manually set the XData, YData, ZData, or CData of a graph, the plot redraws automatically. One frame from the animation looks like this.

For more information, see the refreshdata reference page .

To program the same animation without using refreshdata, the code becomes

c = -pi:.04:pi;
cx = cos(c);
cy = -sin(c);
figure('color','white');
axis off, axis equal
line(cx, cy, 'color', [.4 .4 .8],'LineWidth',3);
title('See Pythagoras run!','Color',[.6 0 0])
hold on
x = [-1 0 1 -1];
y =   [0 0 0 0];
ht = area(x,y,'facecolor',[.6 0 0]);
for j = 1:length(c)
    x(2) = cx(j);
    y(2) = cy(j);
    set(ht,'XData',x)
    set(ht,'YData',y)
    drawnow
end

This code directly assigns plot axis data. Because there is less evaluation going on, it runs visibly faster. The advantage to using refreshdata is that it makes it easier for a program to keep plots in sync when workspace data changes.

Updating Graphs with linkdata Versus refreshdata

The linkdata function, which you can activate and deactivate with the Data Linking tool on the figure toolbar is another way to update a graph when any of its data sources change. When it is turned on, the tool updates axis data continuously and automatically without you needing to call refreshdata. However, data linking is not intended to animate plots; rather, its purpose is to keep different plots in sync and to extend the capabilities of Data Brushing mode, in which you manually highlight observations of interest on a plot. When you use data brushing and data linking together, highlighting observations on one plot causes the them to highlight on other plots which display XData, YData, or ZData from the same data sources.

Data linking is not useful for animation because it does not update plots immediately when data source value changes. Instead, it batches updates at roughly half-second intervals to reduce the communications involved in keeping plots and workspace variables synchronized. Therefore, you should not be using data linking at the same time that you animate graphs using either of the techniques described above.

For more information on data linking and data brushing, see Marking Up Graphs with Data Brushing and Making Graphs Responsive with Data Linking in the MATLAB Data Analysis documentation.

  


 © 1984-2008- The MathWorks, Inc.    -   Site Help   -   Patents   -   Trademarks   -   Privacy Policy   -   Preventing Piracy   -   RSS