Simulation of Pendulum by solving second order ODE in MATLAB
AIM: To write a program for simulating the transient behaviour of a simple pendulum
OBJECTIVES:
- Simulate the transient behaviour of a simple pendulum.
- Create an animation of its motion.
GOVERNING FORMULA:
Ordinary differential equation for oscillating motion of non-linear pendulum,
`(d^2 θ)/(dt^2 )+b/m*(dθ)/dt+g/l*sinθ=0`
Where,
g = gravity in m/s2,
l = length of the pendulum in m,
m = mass of the ball in kg,
b = damping coefficient.
INPUTS:
L = 1 m,
m = 1 kg,
b = 0.05,
g = 9.81 m/s^2,
time span = 0-20 sec,
angular displacement = 0,
angular velocity = 3 rad/sec.
STEPS with CODE:
First we have to define a function for Ordinary Differential Equation for the pendulum
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
After defining the function we write the main program.
In main program the value of each is assigned. The ode45 solver in MATLAB is used to solve the ode for pendulum with damping. The ode45 solver in MATLAB reduce the second order differential equation and gives the result which are then used to plot a Angular displacement vs time graph and simulating the motion of the pendulum.
Main Program
clear all
close all
clc
b=0.05; %Damping co-efficient
g=9.81; %Gravity, m/s^2
l=1; %Length of pendulum, m
m=1; %Mass of the ball, kg
%Initial Condition
%Here, angular displacement=0 & angular velocity = 3
theta_0=[0;3];
%Time span
time_span=linspace(0,20,250);
%Solve ODE
[time,result]= ode45(@(t,theta) ode_func(t,theta,b,g,l,m),time_span,theta_0);
%Plotting
plot(time,result(:,1))
hold on
plot(time,result(:,2))
xlabel('Time(s)')
ylabel('Angular Displacement(rad)')
title('Simple Pendulum')
%Pendulum motion
x=0;
y=0;
for i=1:length(time)
angle=result(:,1)
ANGLE=angle(i);
x1=sin(ANGLE)
y1=-cos(ANGLE)
figure(2)
plot(x1,y1,'.','markersize',50)
hold on
plot([x x1],[y y1],'linewidth',3)
axis([-2 2 -1.5 1.5])
hold off
M(i)=getframe(gcf);
end
%Creating simulation movie
movie(M)
videofile = VideoWriter('pendulum_motion')
open(videofile)
writeVideo(videofile,M)
close(videofile)
RESULT:
The simulation was successfully generated. Link
ERRORS:
Many silly mistakes were made including typo errors.
The ball was not connecting with the string in the simulation. This problem was solved by applying ‘hold on’ command.
Multiple copies of pendulum were being generated. This was solved by applying ‘hold off’ command.