Tutorial · Intermediate · 10 min
Bring it to life: animations
Call animate(seconds) and your whole script re-runs every frame with t set to the time. Anything that depends on t moves.
The time variable t
animate(4)makes a 4-second loop. Usetanywhere — here it shifts a sine wave. The bar under the figure lets you pause, scrub and change the speed.
Try it ↗animate(4) x = linspace(0, 4*pi, 300); plot(x, sin(x - 2*pi*t/4), 'LineWidth', 2) ylim([-1.2 1.2]) title(sprintf('t = %.2f s', t))A point moving along a curve
Draw the path once, then a marker at the position for the current time.
Try it ↗animate(6) s = linspace(0, 2*pi, 400); plot(cos(s), sin(2*s), 'LineWidth', 1.5) hold on p = 2*pi*t/6; scatter(cos(p), sin(2*p), 120, 'r', 'filled') hold off axis equal title('A figure-eight path')Changing a parameter
Time can drive any parameter. Here the damping of an oscillation slowly increases.
Try it ↗animate(8) x = linspace(0, 10, 400); gamma = 0.05 + 0.4 * t / 8; plot(x, exp(-gamma*x) .* cos(3*x), 'LineWidth', 2) ylim([-1 1]) title(sprintf('damping γ = %.2f', gamma))Spinning a 3D view
Make the camera angle depend on
tfor a turntable effect. Use Export → Record animation to save it as a video.
Try it ↗animate(10) [X, Y] = meshgrid(linspace(-3, 3, 45)); surf(X, Y, peaks(X, Y)) shading flat colormap viridis view(36*t, 30) title('A turntable view')