Simple Pendulum ODE Using MATLAB
Solving Simple Pendulum ODE Using MATLAB:-
A simple pendulum having a mass m hanging from a string of length L and fixed at a point . When displaced it a little and released, the pendulum will swing back and forth and follow the periodic motion.
The second order ODE use the following equation -
`d^2(theta) / (dt) +(b/m)*d(theta)/(dt) + (g/l) * sin(theta)= 0`
Main function:-
- Provide all the known input data with time array using \'linspace()\' command and initial condition of pendulum.
- We use an inbuilt MATLAB solver \'ode45\' which is mainly a function of (t) and (theta). In this, we define this function using \'ode_func( input_ parameters )\' then give the initial condition and time span.
- The obtained results from this function will be in 2 column of angular displacement and angular velocity along with the given time.
- Then we plot the obtain data and get two curve of velocity and displacement.
- From here using the values of 1st column of results as `theta`, we create a \'for- end\' loop from 1 up to the length of \'theta\'.
- Here provide the initial position and the path equation for the bob and string.
- Then plot the \'string\' and \'bob\' using initial position and the path equation, after this gave the axis to the pendulum for batter observation.
- Finally, generate an avi. file to see the animation video and saved that.
clear all
close all
clc
b= 0.05;
g= 9.8;
l= 1;
m= 1;
% initial conditions
theta_0 = [0;3];
% time points \'time array\'
t_span= linspace(0,20,200);
% solve ODE & defining the function
[t, results] = ode45(@(t , theta) ode_func(t,theta,b,g,l,m),t_span, theta_0);
figure(1);
hold on
plot(t, results(:,1))
plot(t, results(:,2))
xlabel(\'Time\')
ylabel(\'Plot\')
theta = results(:,1);
ct = 1;
for i = 1: length(theta)
THETA = theta(i);
figure(2);
% initial position
x0 = 0;
y0 = 0;
% position at any ponit
x1= l* sin(THETA);
y1= - l* cos(THETA);
% string
plot([x0 x1], [y0 y1] , \'color\' , \'b\');
hold on
plot ([-.5 .5], [0 0], \'linewidth\',5, \'color\', \'r\');
% bob
plot(x1,y1,\'O\', \'markersize\' ,15, \'markerfacecolor\', \'g\');
axis([-2 2 -2 2]);
hold off
grid on
pause(.03);
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 Defination:-
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
Errors:-
- This error was due to the wrong placing of \'hold on\' command. Hold on should be used after the plot command to avoid this.
- Upper case \'Sin\' is used instead of \'sin\'
- Wrote \'0\' instead of \'o\'.
Link of the animation video:-