Week 3 - Solving second order ODEs
Aim – To write a program to solve a 2nd order ODE that represents the motion of a simple pendulum & to animate its motion.
Inputs from the question:
g = 9.81 m/s2, gravity
L = 1 metre, length of the pendulum
m = 1 kg, mass of the ball
B = 0.05, damping coefficient
Equation given-
-
Procedure –
- Matlab cannot handle 2nd order ode to solce a 2nd order differential equation it must be converted into 2 1st order ode.
- Write a function to convert 2n order ode to 1st order ode’s.
- Use the ode45 solver , pass the function to the ode45 solver as a input value.
- Now we can plot the graph for Time vs displacement and Time vs Angular velocity.
- Nowusing a for loop we can animate the motion of pendulum
Code-
clear all
close all
clc
b=.05;
g=9.81;
m=1;
l=1;
theta_0=[0;3];
t_span=linspace(0,20,100);
% Solving ode using ode45
[t,result]=ode45(@(t,theta) ode_func(t,b,g,l,m,theta), t_span, theta_0)
plot(t,result(:,1),'color','b')
hold on
plot(t,result(:,2),'color','r')
title('Time vs displacement')
xlabel('Time')
ylabel('Angular displacement and angular velocity')
ct=1
theta_1= result(:,1)
for i=1:length(theta_1)
x0=0;
y0=0;
%end coordinates
theta_2=theta_1(i)
x1= l*sin(theta_2);
y1= -l*cos(theta_2);
figure(2)
%pendulum bob
plot([x0 x1],[y0 y1],'o','MarkerSize',10,'MarkerFaceColor','r','MarkerEdgeColor','b','linewidth',5)
hold on
axis([-2 2 -2 2])
%string
line([x0 x1],[y0 y1],'linewidth',4,'color','r')
hold on
%base of pendulum
plot([-1 1],[0 0],'linewidth',4,'color','r')
title('Pendulum');
M(ct)=getframe(gcf);
hold off
ct=ct+1;
end
%To create a movie we will have to create a video file named M
movie(M)
videofile = VideoWriter('pendulum.avi','Uncompressed AVI');
open(videofile)
writeVideo(videofile,M)
close(videofile)
output-

Pendulum animation-
https://drive.google.com/file/d/1cojJLhB-l7Bq6oCGdFSUiBhGkNFzB8Ne/view?usp=sharing
Results-
2nd order differential equation solving by ode45 command gives us a brief idea of how we should divide an equation of second-order differential equation into two first-order differential equations and solve.