Creating Movies and Animations in Matlab

Ming Sun

Ming Sun / October 26, 2022

4 min read––– views

Animation work flow in Matlab

  • Run a simulation or generate data
    • load, sim function
  • Draw/render the scenario at time t[k]
    • plot, plot3, surf, hold on, clf (clear figure)
  • Take a snapshot of scenario
    • getframe
  • Advance time to time t[k+1]
    • continue: to skip some of the data to avoid large size video output
  • Repeat the above process
  • Once it is done, save the movie
    • videowriter, writevideo
clear; clc; close all;

%% Step 1: Generate data
t = linspace(0, 2*pi, 100);
x = 5*cos(t);
y = 2*sin(t);
z = t;

%% Step 2: Draw/Render the Scenario
figh = figure;

for k=1:length(t)
%     Wipe the slate clean so we are plotting with a black figure

%     Extract the data at the current time
t_k = t(k);
x_k = x(k);
y_k = y(k);
z_k = z(k);

% plot the current location of the particle
plot3(x_k, y_k, z_k, 'go', 'LineWidth',3, 'MarkerSize', 15)

% plot the entire trajectory
hold on;
plot3(x, y, z, 'b-', 'LineWidth',2)

% Decorate the plot
grid on;
title(['Particle at t= ', num2str(t_k), ' seconds'])

% force Matlab to draw the image at this point
% drawnow
% pause(0.2)
movieVector(k) = getframe(figh, [10 10 520 400]);

%% Step 4: Advance Time
% Do not need to do anything


%% Step 5: save the movie
myWriter = VideoWriter('curve', 'MPEG-4');
myWriter.FrameRate = 20;

% Open the videowritter object, write the move, and close the file
writeVideo(myWriter, movieVector);


[1] Creating Movies and Animations in Matlab - Christopher's youtube tutorial

[2] animation.m - Matlab script download

Google ScholarLinkedIn