Oscillating Pendulum With Solving second order ODEs
For solving this challenge first create a function according to the Pendulum\'s ODE.
`(d^2theta)/(dt^2) + b/m(d theta)/dt + g/l sin theta = 0`
where:
`b =`damping coefficient`
`m =`mass of ball in kg`
`l =`length of the pendulum in m`
`g =`gravity in m/s^2`
Function is
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 creating ODE function, Now write the programme.
% Writing a code to oscillate the pendulum.
clear all
close all
clc
%inputs
b = 0.05; %Damping Coefficient
g = 9.81; %Gravity m/s^2
m = 1; %Mass of the Pendulum in kg
l = 1; %Length of the string attached to pendulum in meters
%initial conditions
theta_0 = [0;3]; %[angular displacement=0;angular velocity=3]
%time points
t_span = linspace(0,20,500); %pendulum oscillates between 0-20 seconds
%solve ODE
[t,result] = ode45(@(t,theta) ode_func(t,theta,b,g,l,m),t_span,theta_0);
%plotting the graph
figure(1)
subplot(2,1,1)
p1 = plot (t,result(:,1),\'linewidth\',2,\'color\',\'b\');
xlabel(\'\\bf{Time}\');
ylabel(\'\\bf{Theta [\\theta]}\');
title(\'Angular Displacement [{\\theta}] v/s Time\');
hold on
subplot(2,1,2)
p2 = plot(t,result(:,2),\'linewidth\',2,\'color\',\'g\');
xlabel(\'\\bf{Time}\');
ylabel(\'\\bf{Velocity}\');
title(\'Angular Velocity v/s Time\');
legend([p1(1),p2(1)],\'angular displacement\',\'angular velocity\')
%pendulum simulation using ode
theta = result(:,1);
ct=1;
%%creating a for loop for oscillating the pendulum
for i=1:length(result)
THETA = result(i,1);
%initial boundary conditon
x0=0;
y0=0;
%Defining x and y coordinates
x1= l*sin(THETA);
y1= -l*cos(THETA);
figure(2)
hold on
plot([x0 x1],[y0 y1],\'linewidth\',4);
plot(x1,y1,\'-o\',\'markersize\',30,\'markeredgecolor\',\'r\',\'markerfacecolor\',[0.6 0.6 0.6]);
plot(x0,y0,\'-*\',\'markersize\',3,\'markeredgecolor\',\'r\',\'markerfacecolor\',[0.6 0.6 0.6]);
title(\'Oscillating Pendulum\');
axis([-2 2 -2 0]);
pause(0.005);
M(ct)=getframe(gcf);
ct=ct+1;
clf() %clf() code is used for clearing the current graphic image
end
%%creating the animation and movie(avi)
movie(M);
videofile = VideoWriter(\'second_ode_pendulum.avi\',\'uncompressed AVI\');
open(videofile)
writeVideo(videofile,M)
close(videofile)
Here are the programme output-