Ron Bakker/MathLabHelp
Open MathLab ↗

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.

  1. The time variable t

    animate(4) makes a 4-second loop. Use t anywhere — here it shifts a sine wave. The bar under the figure lets you pause, scrub and change the speed.

    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))
    Try it ↗
  2. A point moving along a curve

    Draw the path once, then a marker at the position for the current time.

    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')
    Try it ↗
  3. Changing a parameter

    Time can drive any parameter. Here the damping of an oscillation slowly increases.

    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))
    Try it ↗
  4. Spinning a 3D view

    Make the camera angle depend on t for a turntable effect. Use Export → Record animation to save it as a video.

    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')
    Try it ↗