A simple demonstration video of the VideoWrite command in MATLAB. The motion of a pendulum is animated.
Here are the scripts that have been used to generate the video:
1. Function file of the equation of motion of a pendulum:
function [ydot]=pendulum(t,y,b,m,g,L) % defining the function; theta is taken as y(i,1) and y(i,2) will be the angular velocity at corresponding times t(i) %
ydot=zeros(2,1); % defining ydot as a column vector %
ydot(1)=y(2); % defining the first time derivative of angular displacement %
ydot(2)=-(b/m)*y(2)-(g/L)*sin(y(1)); % The equation to be solved %
end
2. Script for generating the plots of angular displacement, angular velocity and the video:
clear all
close all
clc
t=[0 20]; % Starting and ending time %
y0=[0 3]; % Initial Conditions in angular displacement and angular velocity %
b=0.05; % damping coefficcient %
m=1; % mass of the ball in kg %
g=9.81; %acceleration due to gravity in m/s^2 %
L= 1; % Length of the pendulum in m %
% calling the ode 45 solver %
[t,y]=ode45(@(t,y) pendulum(t,y,b,m,g,L), t,y0);
z=size(y); % finds the size of the solution matrix %
% Co-odinates of the Pendulum Pivot %
Xo=0;
Yo=0;
for i=1:z(1) % Plotting Pendulum Coordinates for different time intervals %
X(i)=L*sin(y(i,1));
Y(i)=-L*cos(y(i,1));
end
% plotting the angular displacement in figure 1 %
figure(1)
plot(t,y(:,1),'linewidth',1)
grid on
xlabel('time, t (s)')
ylabel('Angular Displacement, \theta (rad)')
% plotting the angular velocity in figure 2 %
figure(2)
plot(t,y(:,2),'linewidth',1)
grid on
xlabel('time, t (s)')
ylabel('Angular Velocity, \omega (rad/s)')
figure(3)
% Making the Animation of the Pendulum using figure 3 %
animation=VideoWriter('pendulum_animation.avi','Uncompressed AVI'); % Using the VideoWriter command to create a .avi video with the filename 'pendulum_animation' %
open(animation); % opens the file pendulum_animation.avi for writing %
for i=1:z(1) % generate a set of z frames by using the for loop %
plot([-0.25 0.25],[0 0])
hold on
plot([Xo X(i)],[Yo Y(i)],'linewidth',1.5)
hold on
plot(X(i),Y(i),'.','markersize',50) % ith frame of the plot of the pendulum coordinate at a particular instant of time t(i) %
xlim([-1.25 1.25])
ylim([-1.25 0.25])
hold off
M(i)=getframe(gcf); % Captures the current plot in one frame %
writeVideo(animation,M(i)); % Writing video data to the file %
end
close(animation) % closes the file pendulum_animation.avi after writing %