Home > Resources > Making Animation with MATLAB > 3. Animation of a moving point
Making Animation with MATLAB

3. Animation of a moving point

Code 1 below is an example MATLAB script that produces an animation of a point moving along x-axis.

animation_point.m
% animation_point.m

clear; close all;

% Create motion data -- (1)
t = 0:0.001:1;   % Time data
x = sin(2*pi*t); % Position data

% Draw initial figure -- (2)
figure(1);
h = plot(x(1), 0, 'o', 'MarkerSize' ,20, 'MarkerFaceColor', 'b');
xlim([-1.5, 1.5]);
ylim([-1.5, 1.5]);

% Animation loop -- (3)
for i = 1:length(x)
    set(h, 'XData', x(i));
    drawnow;
end
Code 1: Example MATLAB script that produces an animation of a moving point

First at (1), the motion data of the point are created. Next at (2), the initial point is drawn by the plot command and the handle of the chart line object is saved in the variable h. Finally in the loop at (3), the value of XData property of the chart line object is replaced and the figure is updated with drawnow command resulting in animation. This is the basic code to make an animation in MATLAB.

The animation produced by this script is shown in Movie 1.




Movie 1: Animation of a moving point
Sponsor Link