|| Second Order ODE of a Pendulum in Motion using MATLAB ||
OBJECTIVE:-
To write a program that solves the Second Order ODE of a pendulum in motion, and create an animation related to it.
THEORY:-
A Second order differential equation is an equation involving the unknown function y, its derivatives y' and y'', and the variable x.
According to the question the equation is,
where,
b = damping
m = mass
g = gravity
l = length
It is given that, angular velocity is = 3 rad/s, at time t = 0 sec.
MATLAB_Code :
1. Function Code :
function [dtheta_dt] = ode_function_problem(t, theta,l,m,b,g)
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 Code :-
clear all
close all
clc
l = 1;
m = 1;
b = 0.05;
g = 9.81;
%initial_stage
theta0 = [0;3];
%Time_of_motion
t_motion = linspace(0,20,500);
%To_solve_ODE
[t, results] = ode45(@(t,theta) ode_function_problem(t,theta,l,m,b,g), t_motion, theta0);
figure(1)
plot(t,results(:,1),'color','b')
hold on
plot(t,results(:,2),'color','r')
plot(results(:,1),results(:,2))
ylabel('Angular Velocity')
xlabel('time')
legend('position Radian','angular velocity')
hold off
grid on
figure(2)
ct=1;
for i = 1:length(t_motion)
x0 = 0;
y0 = 0;
x1 = 1*sin(results(i,l));
y1 = -1*cos(results(i,1));
plot([x0 x1],[y0 y1],[-0.5 0.5],[0 0],'linewidth',3)
hold on
plot(x1, y1,'o','MarkerSize',30,'MarkerFacecolor','r')
axis([-1.5 1.5 -1.5 0.5])
grid on
pause(0.0001)
hold off
M(ct) = getframe(gcf);
ct = ct+1;
end
movie(M)
videofile = VideoWriter('ODE_Pendulum.avi','Uncompressed AVI');
open(videofile)
writeVideo(videofile,M)
close(videofile)
EXPLAINATION OF THE CODE :-
- Take input datas given in the question, as l,m,b,g .
- Taking initial stage for time and angular velocity as '0' & '3' resp.
- Taking time span or time in motion as 20 sec. and seperating it in 500 interval using linspace command.
- In an another window, taking function program as ''ode_function(t,theta,l,m,b,g)'' .Now, Differentiating it for two times as it is a 2nd order differntial equation we get, two values. substitute those two values in the funtion.
Use the command "de45" to exeute the ODE function. - "plot" the figure1 using two results one for the whole row and 1st column and 2nd for whole row and 2nd column, And specify labels accordingly.
- Now, for figure2 , take a for loop command, and plot it.
- Use, "Markersize" command to set the pendulum size "o" for circular shape of pendulum and "MarkerFacecolor" for the color of the pendulum.
- Use, movie command and getframe command to stitch the frames and to make the whole movie through it.
OUTPUT:-
Fig.1. Angular velocity Vs Time Graph
Fig.2 Pendulum in Motion
CONCLUSION:-
So, the ODE based Code is Successfully been converted into the pendulum in motion.