Animation
An animation is a plot that changes over time: a simulation running step by step, a signal scrolling past, a surface morphing as a parameter grows. MATLAB has no special "animation object". You draw the first frame, then repeatedly change the data of the plotted objects and ask the screen to refresh. This lesson covers that loop, the shortcuts for common cases, and how to save the result as a GIF or video.
Note: animations need a graphics window, so the drawing loops here don't run in the browser. The runnable parts compute the frames' data, and one writes a real animated GIF without any window at all.
The update loop
The fast, flicker-free pattern has three steps:
- Draw once and keep the handle that
plot(orsurf,scatter…) returns. - In a loop, change the handle's
XData/YData/ZDatawithset. - Call
drawnowto render the change (andpauseif you need to slow it down).
x = linspace(0, 2*pi, 200);
h = plot(x, sin(x), 'LineWidth', 1.5); % step 1: draw and keep the handle
axis([0 2*pi -1.2 1.2]) % fix the limits so they don't jump
for k = 1:120
phase = 2*pi * k / 120;
set(h, 'YData', sin(x - phase)); % step 2: change the data
drawnow % step 3: show it
pause(0.02) % about 50 frames per second at most
endTwo details make or break an animation. Fix the axis limits before the loop, otherwise the automatic limits change from frame to frame and the picture jumps. And don't call plot inside the loop: creating a new line object every frame is many times slower than updating one, and with hold on the old lines pile up.
MATLAB also lets you write h.YData = sin(x - phase) (dot notation on graphics objects). In Octave, graphics handles are plain numbers and dot notation doesn't work on them, so portable code uses set(h, 'YData', ...) and get(h, 'YData').
| Command | Role |
|---|---|
drawnow |
Process pending graphics updates and redraw now |
drawnow limitrate |
MATLAB: redraw at most about 20 times a second, skipping frames if the loop is faster |
pause(s) |
Wait s seconds (also redraws); sets the pace |
set(h, 'XData', x, 'YData', y) |
Move or reshape an existing object |
comet(x, y), comet3(x, y, z) |
A ready-made animation tracing a path |
comet(x, y) is the quickest way to watch a trajectory being traced: it animates a "comet" with a short tail along the path, with no loop to write.
Computing the frames: a bouncing ball
Animations usually come from a simulation that produces one state per time step. Separating the two (compute everything first, then draw) keeps the physics testable and the drawing loop simple. Here a ball drops from 10 m and loses 20% of its speed at each bounce:
dt = 0.01; g = 9.81; e = 0.8; % time step, gravity, bounce factor
T = 0:dt:5;
height = zeros(size(T));
y = 10; v = 0; bounces = [];
for k = 1:numel(T)
height(k) = y;
v = v - g*dt; % update velocity, then position
y = y + v*dt;
if y < 0 % hit the floor: reflect and lose energy
y = -y;
v = -e*v;
bounces(end+1) = T(k);
end
end
fprintf('%d frames, bounces at t = %s s\n', numel(T), mat2str(bounces, 3));
after = T > bounces(1) + 0.05 & T < bounces(2);
fprintf('Highest point after the first bounce: %.2f m\n', max(height(after)));501 frames, bounces at t = [1.42 3.71] s
Highest point after the first bounce: 6.46 m
Physics predicts a first impact at √(2·10/9.81) ≈ 1.43 s and a rebound to 0.8² × 10 = 6.4 m, so the simulation is on track. Drawing it is now a short loop over the stored heights, showing every fourth step to keep the frame rate reasonable:
h = plot(0, height(1), 'o', 'MarkerSize', 12, 'MarkerFaceColor', [0 0.45 0.74]);
axis([-1 1 0 10.5]); ylabel('Height (m)')
for k = 1:4:numel(T)
set(h, 'YData', height(k));
title(sprintf('t = %.2f s', T(k)))
drawnow
endGrowing lines: animatedline (MATLAB)
For a line that grows point by point (live sensor data, a trace being drawn), MATLAB has animatedline, which stores the points efficiently and adds new ones with addpoints:
% MATLAB only (Octave 11 doesn't have animatedline)
h = animatedline('Color', 'r', 'LineWidth', 1.5);
axis([0 10 -1 1])
for t = linspace(0, 10, 300)
addpoints(h, t, sin(2*t) * exp(-t/5));
drawnow limitrate
endThe same effect works in both programs by appending to the line's data. It is slower for very long lines, since all the data is copied each time, but fine for a few thousand points:
h = plot(NaN, NaN, 'r', 'LineWidth', 1.5); % an empty line to start from
axis([0 10 -1 1])
for t = linspace(0, 10, 300)
set(h, 'XData', [get(h, 'XData'), t], ...
'YData', [get(h, 'YData'), sin(2*t) * exp(-t/5)]);
drawnow
endanimatedline also takes 'MaximumNumPoints', which drops the oldest points, ideal for a scrolling display of the last few seconds of data.
Recording: getframe, GIFs and videos
To save an animation, capture each frame with getframe, which returns a structure whose cdata field holds the pixels as an RGB uint8 array:
| Goal | How |
|---|---|
| Replay in MATLAB/Octave | F(k) = getframe(fig); in the loop, then movie(F) |
| Animated GIF | Convert each frame to indexed colour and imwrite with 'WriteMode', 'append' |
| MP4/AVI video | v = VideoWriter('out.mp4', 'MPEG-4'); open(v); writeVideo(v, frame); close(v) (MATLAB; Octave needs the video package) |
An animated GIF is a series of indexed images in one file. The first imwrite call creates the file and sets the looping, and later calls append frames. You don't even need a figure: here each frame is a small matrix with a dot drawn into it, value 1 for the background colour and 2 for the dot:
W = 40; H = 30;
map = [1 1 1; 0 0.45 0.74]; % colour 1 = white, colour 2 = blue
[cols, rows] = meshgrid(1:W, 1:H);
for k = 1:12
frame = ones(H, W); % all background
cx = 4 + 3*(k - 1); % the dot moves right by 3 pixels
frame((cols - cx).^2 + (rows - 15).^2 <= 9) = 2;
if k == 1
imwrite(frame, map, 'dot.gif', 'DelayTime', 0.1, 'LoopCount', Inf);
else
imwrite(frame, map, 'dot.gif', 'DelayTime', 0.1, 'WriteMode', 'append');
end
end
info = imfinfo('dot.gif');
fprintf('dot.gif: %d frames of %d x %d pixels\n', numel(info), info(1).Width, info(1).Height);
first = imread('dot.gif', 1);
fprintf('frame 1 is %s with values %s\n', class(first), mat2str(unique(first)'));dot.gif: 12 frames of 40 x 30 pixels
frame 1 is uint8 with values [0 1]
Notice that the values read back are 0 and 1, not 1 and 2. Indexed images stored as double use 1-based colormap indices (MATLAB style), while uint8 indexed images, the form image files use, are 0-based. Add 1 to the uint8 values before using them as MATLAB indices.
When the frames come from a figure, convert them first: [idx, cmap] = rgb2ind(frame2im(getframe(fig)), 256); reduces the RGB capture to at most 256 colours, and imwrite(idx, cmap, 'out.gif', ...) writes it as above. 'DelayTime' is in seconds per frame; 0.04 s gives 25 frames per second.
Summary
- Draw once, keep the handle, update
XData/YDatawithset, and calldrawnow. Fix the axis limits first. - Compute the simulation into arrays, then animate the stored frames.
animatedline/addpoints(MATLAB) grows a line efficiently; appending toXData/YDataworks everywhere.getframecaptures frames, andimwrite(..., 'WriteMode', 'append')builds an animated GIF.VideoWritermakes videos in MATLAB.
Next: Control Flow for the logic that drives loops like these. Learn more: Random Numbers & Simulation for simulations worth animating.
Test yourself
Why should an animation loop update the handle with set(h, 'YData', ...) instead of calling plot each frame?
plotcan't be called inside a loop- Updating an existing object is much faster and doesn't pile up old lines
setmakes the colours brighterplotignores drawnow
What does drawnow do?
- Clears the figure
- Forces MATLAB to render pending graphics changes immediately
- Saves the current frame
- Starts a new figure
When writing an animated GIF frame by frame, which option adds frames after the first?
'Append', true'WriteMode', 'append''Frames', k'LoopCount', k