Project

Solving second order ODE and Animation of Simple Pendulum

In Engineering, ODE is used to describe the transient behavior of a system. A simple example is a pendulum The way the pendulum moves depends on the Newtons second law. When this law is written down, we get a second order Ordinary Differential Equation that describes the position of the "ball" w.r.t time.

The program written here solves the following ODE.

This ODE represents the equation of motion of a simple pendulum with damping. In the above equation

  • g = gravity in m/s2,
  • L = length of the pendulum in m,
  • m = mass of the ball in kg,
  • b=damping coefficient.

Constants used L=1 metre, m=1 kg, b=0.5. g=9.81 m/s2. Simulate the motion between 0-20 sec, for angular displacement=0,angular velocity=3 rad/sec2 at time t=0.1.

clear all
close all
clc

%constants
b=0.5;
g=9.81;
m=1;
l=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);

x0=0;
y0=0;
THETA_1=results(:,1);

ct=1
for i=1:length(t_span)
    r=THETA_1(i);
    
    x1=1*sin(r);
    y1=-1*cos(r);
    
    plot([x0 x1],[y0 y1],'linewidth',1,'color','bla')
    viscircles([x1 y1],0.05)
    rectangle('position',[-0.4 0 0.8 0.2],'facecolor','c')
    title('simple pendulum')
    line([0 0],[-3 0],'color','blue','linestyle','--')
    axis([-1 1 -1.4 0.2])
    
    M(ct)=getframe(gcf)
    ct=ct+1
end

movie(M)
videofile=VideoWriter('pendulum_animation.avi')
open(videofile)
writeVideo(videofile,M)
close(videofile)

%displacement and velocity against time
figure(2)
plot(t,results(:,1),'color','r')
hold on
plot(t,results(:,2))
grid on
xlabel('time (in sec)')
legend('displacement','velocity')
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
 

The plot of Displacement and Velocity is below .

The link for the animation of the pendulum is below.

https://youtu.be/9WpFmvM8TSQ

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.