Week 3 - Solving second order ODEs
clear all
close all
clc
%%parametric varaiable for pendulum
b=0.05;% damping
g=9.81;% gravity
l=1;%length of the pendulum
m=1;%mass of the pendulum
theta_0= [0;3]; %%initial condition
t_span=linspace(0,10,600);% simulation time duration
[t,result]= ode45(@(t,theta) ...
ode_pro(t,theta,b,g,l,m),t_span,theta_0); % differential equation solver
% plot(t_span,result(:,1))% plotting time vs dispalcement
% hold on
% plot(t_span,result(:,2)) %plotting time vs velocity
% ylabel('plot') %y-axis labelling
% xlabel('time')%x-axis labelling
%Animation of pendulum
o=[0 0] % origin of the pendulum
axis(gca,'equal') %axis with equal spacing
axis([-1.6 2 -1.6 1.6])%axis value with constrain spacing
grid on
ct=1% inital iteration
for i=1:length(t)% for loop
p=l*[sin(result(i)) -cos(result(i))]% mass point of the pendulum
circle= viscircles(o,0.1)%dispaly of circle with radius 'r'at the origin
pend=line([o(1) p(1)],[o(2) p(2)]) %line between centre of origin and centre of end point
ball= viscircles(p,0.5)%dispaly of circle with radius 'r'at the end of line
M(ct)= getframe(gcf)%capturing frames for each iteration
% if conditions to delete the previous displayed pendulum
if i<length(t)
delete(pend)
delete(ball)
delete(circle)
ct=ct+1
end
end
movie(M)%motion didplay of arms
videofile= VideoWriter('pendulum.avi');%saving videos
open(videofile)
writeVideo(videofile,M)
close(videofile)
function [dtheta_dt] =ode_pro(t,theta,b,g,l,m)%calling parameters
theta1=theta(1)%assigning the theta 1
theta2=theta(2)%assigning the theta 2
dtheta1_dt=theta2;% assigning the displacment value to the derivative
dtheta2_dt= -(b/m)*theta2-(g/l)*sin(theta1);% assigning the velocity value to the derivative
dtheta_dt=[dtheta1_dt; dtheta2_dt];% converting values into matrix
end
output
Figure 1 shows that initially, the displacement was zero(0) and velocity was 3 m/s. The total duration of the simulation is 20 sec and their animation link is given below:
https://www.youtube.com/watch?v=_zRii5_VO5s

Figure 1 displacement and velocity graph of the pendulum