Week 3 - Solving second order ODEs
AIM:
To solve a 2nd Order Differential Equation of a simple pendulum using MATLAB.
OBJECTIVE:
- To write a program to solve the ODE of the motion of a simple pendulum using MATLAB.
- Plot the graph of the displacement and velocity.
- Create a simulation of the pendulum in motion.
THEORY:
A 2nd Order Differential Equation is an equation involving the unknown function y, its derivatives y' and y'', and the variable x. Which is written as,
Where,
b = damping coefficient.
m = mass of the bob in Kg.
g = the gravity in m/s^2.
l = length of the string in m.
Breaking down the 2nd Order Differential Equations into two 1st Order Differential Equations,
From this derivation we have defined θ1 and θ2.
MATLAB Program:
% ODE function
function [dtheta_dt] = ode_func(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
%Solving second order differential
close all
clc
%Inputs
b = 0.05;
g = 9.81;
l = 1;
m = 1;
%Initial condition
theta_0 = [0;3];
%Time points
t_span = linspace (0,20,500);
%solve ODE
[t, results] = ode45(@(t,theta) ode_func(t,theta,b,g,l,m),t_span,theta_0);
%Plotting the graph
plot(t,results(:,1))
hold on
plot(t,results(:,2))
xlabel('Time')
ylabel('Plot')
legend("Angular displacement","Angular velocity")
% Writing a for loop to make the animation
ct = 1;
for i = 1:length(results(:,1))
x0 = 0;
y0 = 0;
x1 = l*sin(results(i,1));
y1 = -l*cos(results(i,1));
% Plotting the animation
figure(2)
plot([-1 1],[0 0],'linewidth',5)
hold on
plot([x0 x1],[y0 y1],'linewidth',3)
hold on
plot(x1,y1,'o','markersize',20,'markerfacecolor','y')
axis([-2 2 -2 2])
pause(0.03)
hold off
M(ct) = getframe(gcf);
ct = ct+1;
end
% Converting the animation into a movie
movie(M)
videofile = VideoWriter('pendulum_oscillation.avi','Uncompressed AVI');
open(videofile)
writeVideo(videofile,M)
close(videofile)
Conclusion:
We were able to solve the 2nd Order Differential equation of a pendulum in motion using MATLAB.
From the solution we were able to plot a graph of the oscillation of the pendulum.
We were also able to create a video of the pendulum in motion
https://youtu.be/u0k9Mf43kzk