Home > Resources > Making Animation with MATLAB > 12. Saving animation in video file
Making Animation with MATLAB

12. Saving animation in video file

To save an animation in a video file such as an AVI file, we can use VideoWriter object. Code 1 shows a MATLAB script that saves the animation of a moving point of Section 3 in an AVI file. In order to get a desirable result, the time step (Time data) and the property values of the VideoWriter object may have to be adjusted appropriately.

animation_point_avisave.m
% animation_point_videowriter.m

clear; close all;

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

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

% Create & open video writer
vw = VideoWriter('animation_point.avi');
vw.Quality = 100;
vw.FrameRate = 60;
open(vw);

% Animation loop
for i = 1:length(x)
    set(h, 'XData', x(i));
    drawnow;

    % Write each frame to video
    frame = getframe(gcf);
    writeVideo(vw, frame);
end

% Close video writer
close(vw);
Code 1: MATLAB script that saves the animation of a moving point of Section 3 in an AVI file

Sponsor Link