Week 3 - Solving second order ODEs
Aim
write a program that solves the following ODE and simulates the pendulum motion
`(d^2 theta)/dt^2+b/m*(d theta)/dt+g/L*sin theta=0`
Theory
Second order differential equation is a specific type of differential equation that consists of a derivative of a function of order 2 and no other higher-order derivative of the function appears in the equation.
Code Explanation
1. The input variables are allocated.
- g = gravity in m/s2
- L = length of the pendulum in m
- m = mass of the ball in kg
- b=damping coefficient
2. Initial Conditions are mentioned.
- angular displacement=0
- angular velocity=3 rad/sec
3. Set a time period of 0-20sec with 100 iterations in it.
4. ode45 solver is used to solving the 2nd ODE
5. This is applied to make a function called ode_fun, which is called to
calculate the angular displacement along the change in time.
6. The pendulum is plotted using the Plot command.
7. The animation is created accordingly
Main Code
clear all
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,100);
% Solve ODE
[t,results]= ode45(@(t,theta)ode_func(t,theta,b,g,l,m),t_span,theta_0);
a = results(:,1);
ct=1;
for i=1:length(a)
x0=0;
y0=0;
x1 = l*sin(a(i));
y1 = -l*cos(a(i));
plot([x0 x1],[y0 y1],'LineWidth',4,'Color','g')
hold on
plot([-0.5 0.5],[0 0],'LineWidth',8,'Color','b')
plot(x1,y1,'Marker','.','Color','r','MarkerSize',45,'MarkerFaceColor','k')
hold off
axis([-1 1 -1 1])
pause(0.03);
title('Animation of pendulum')
M(ct)=getframe(gcf);
ct=ct+1;
end
movie(M)
videofile=VideoWriter('ode_main.avi','Uncompressed AVI');
open(videofile);
writeVideo(videofile,M);
close(videofile);
Function Code
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
Error Faced

Result
The animation of the pendulum is created.
Google drive link: https://drive.google.com/drive/folders/1IP20feWQ2NljK1hqU2y1nQWhgRpdP4Oz