Challenge

Week 3 - Solving second order ODEs

Pendulum: A pendulum is a body suspened from a fixed point so that it can swing back and forth under the influence of gavity.

Objective: Write a program to solve the equation of motion of simple pendulum with damping ODE.

b = damping coefficient 

g = gravity 

L = length 

m = mass

To solve the ODE we need to reduce order of equation into lower order.

Let 

 

There for by solving it 

Given Details:

b = 0.05

L = 1 m 

M = 1Kg

g = 9.81 m/s^2

Matlab code

1. Code function ode45

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

2. Main Program 

%Input 
b = 0.05;               %damping coeficient
g = 9.81;               %gravity
l = 1;                  %length of pendulum
m = 0.1;                %mass of bob

%Initial Cndition 
theta_0 = [0;3]

%time 
t_span = linspace(0,20,500);

%Solve ODE function 
[t,result] = ode45(@(t,theta) ode_func(t,theta,b,g,l,m),t_span, theta_0);

%Plotting 
figure(1)
plot(t,result(:,1))
hold on 
plot(t,result(:,2))
ylabel('Velocity (Red) & Displacement (Blue)')
xlabel('time')

%Animation
ct = 1
for i = 1:length(result(:,1))
  x0 = 0;
  y0 = 0;
  x1 = l*sin(result(i,1)+pi);
  y1 = l*cos(result(i,1)+pi);
  figure(2)
  
  plot([x0 x1],[y0 y1],'linewidth',4)
  axis([-2 2 -2 2])
  hold on 
  plot([-1 1],[0,0],'linewidth',5,'color','r')
  hold off
  M(ct) = getframe(gcf)
  ct = ct+1;
end

%Movie & vedio file 
Movie (M) 
videofile = VideoWriter('ODE.avi','Uncompressed AVI');
open(videofile)
writeVideo(videofile,M)
close(videofile)

Code Explanation :

1.Assign the given details as variables. Time span of the simple pendulum 500 values take in 10 time period is given using linespace command

2.Then use ode45 function and call ode_func to the main program.

3.Plot the velocity and displacement grapgh using plot command 

4.Use the loop to create the animation of the pendulum.

5.To change the values in the loop counter command is used. Vedio writer command is used to create the vedio file.

Result :

Your portfolio, next

Ship work like this
in your own course.

Talk to a career counsellor

Free 20-minute call. We'll map the right course to where you want to work.

By submitting you agree to our Terms and Privacy Policy.

Talk to a career counsellor

Free 20-minute call. We'll map the right course to where you want to work.

By submitting you agree to our Terms and Privacy Policy.