0
0
MATLABdata~5 mins

Animation basics in MATLAB

Choose your learning style9 modes available
Introduction

Animation helps show how data changes over time. It makes patterns easier to see and understand.

Showing how a line graph changes step by step.
Visualizing moving points on a map.
Demonstrating changes in a bar chart over days.
Explaining how a function behaves as input changes.
Syntax
MATLAB
figure;
h = plot(x, y);
for k = 1:length(x)
    set(h, 'YData', y(1:k));
    drawnow;
    pause(0.1);
end

figure; opens a new window for the plot.

drawnow; updates the figure immediately to show changes.

Examples
This example animates a sine wave by gradually showing points.
MATLAB
x = 1:10;
y = sin(x);
figure;
h = plot(x, y);
for k = 1:length(x)
    set(h, 'YData', y(1:k));
    drawnow;
    pause(0.2);
end
This example animates a moving sine wave by shifting it over time.
MATLAB
x = linspace(0, 2*pi, 100);
y = sin(x);
figure;
h = plot(x, y);
for k = 1:100
    set(h, 'YData', sin(x + k*0.1));
    drawnow;
    pause(0.05);
end
Sample Program

This program creates a sine wave animation by gradually revealing the wave from left to right.

MATLAB
x = 0:0.1:2*pi;
y = sin(x);
figure;
h = plot(x, zeros(size(y)));
title('Animating a Sine Wave');
for k = 1:length(x)
    set(h, 'YData', y .* (x <= x(k)));
    drawnow;
    pause(0.05);
end
OutputSuccess
Important Notes

Use pause to control animation speed.

drawnow forces MATLAB to update the figure immediately.

Pre-define the plot handle to update data efficiently without creating new plots.

Summary

Animation shows data changes over time visually.

Use set to update plot data inside a loop.

Control speed with pause and refresh with drawnow.