Week 3 - Solving second order ODEs
AIM: To solve the second order odes function using Matlab for simple pendulum and animation video.
Objective : To write a code for following equation of motion of simple pendulum.

Pendulum geometry: Length(l) = 1 meter
Mass(M) = 1 kg.
Damping coiefficient(b) = 0.05
Acceleration due to gravity = 9.81m/s2
Time period = 0-20s
displacement = 0, velocity = 3 rad/sec at t= 0
sub code:
% odes function
function dtheta_dt = ode_funs(t,theta,b,g,l,m);
theta1 = theta(1);
theta2 = theta(2);
dtheta1_dt = theta2;
dtheta2_dt = -(b/m)*theta2-(g/l)*sin(theta1);
dtheta_dt = [ dtheta1_dt ; dtheta2_dt ];
end
Main code:
clear all
close all
clc
%code for odes
%input
%Damping co-efficient
b = 0.05;
% Acceleration due to gravity(m/m^2)
g = 9.81;
%Mass (kg)
m = 1;
%length(m)
l = 1;
%initial condition
theta_0 = [0;3]
% Time points
t_span = linspace(0,20,200)
%Solving ODES
[t,results] = ode45(@(t,theta) ode_funs(t,theta,b,g,l,m), t_span,theta_0);
%plotting
figure(1)
plot(t,results(:,1))
hold on
plot(t,results(:,2))
xlabel('Time')
ylabel('angural velocity(rad/s)/displacement(rad)')
legend('displacement','angular velocity')
%Animation
ct = 1;
for i = 1:length(results(:,1))
x0 = 0
y0 = 0
x1 = l*sin(results(i,1)+pi);
y1 = l*cos(results(i,1)+pi);
figure(2)
plot([x0,x1],[y0 y1],'-o','MarkerSize',10,'MarkerFaceColor','r','MarkerEdgeColor','r','linewidth',5)
axis([-2 2 -2 2])
hold on
plot([-1 1],[0 0],'linewidth',10,'color','b')
M(ct) = getframe(gcf)
hold off
ct = ct+1;
end
%Movie & videofile
movie(M)
v_f = VideoWriter('pendulum_1.avi','Uncompressed AVI')
open(v_f)
writeVideo(v_f,M)
close(v_f)
Explanation :
sub code is function program of the second order ODES is simplefied to the first order odes.
Then in main program pendulum fixed parameters are like length,mass, damping coefficient.
t_span command in which 200 value are taken between 0 to 20 times period.
odes45 command is used that solve ordinary or partial differential equations using a numerical method.
plot command is used to plot graph between velocity , displacement vs time.
for animation command used are movie,videoFile,writeVideo,close video .
PLOT:

VIDEO LINK: https://youtu.be/iQEbW_Xad9I