Simple Pendulum Simulation
Creating a function to solve ordinary differential equation
%creating a function
function[dtheta_dt]=ode_fun(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
Now writing a code to simulate the simple pendulum.
clear all
close all
clc
%input variables
%damping coefficient
b=0.05;
%acceleration due to gravity inm/s^2
g=9.81;
%length of the string in m
l=1;
%mass in kg
m=1;
%initial condition
%theta_0=[angular displacement at 0; angular velocity at 0];
theta_0=[0;3];
%time points
%time interval is between 0-20 seconds
t_span=linspace(0,20,100);
%solving ode function
%final x = ode45(@(interval) ode function, time span, initial conditions)
[t,x]=ode45(@(t,theta)ode_fun(t,theta,b,g,l,m),t_span,theta_0);
%plotting
hold on
%displacement plot
plot(t,x(:,1),'Color','r')
%velocity plot
plot(t,x(:,2),'Color','b')
%labelling
legend('angular displacement','angular velocity')
xlabel('time')
ylabel('displacement/velocity')
%animation
X=0;
Y=0;
ct=1; %counter for representation of each and every frame
%using for loop to get the instantaneous position of the pendulum bob
for i=1:length(t_span) %no. of iterations
X1=l*sin(x(i,1)); %instantaneous position of bob in x-axis
Y1=-l*cos(x(i,1)); %instantaneous position of bob in y-axis
figure(2) %opening another figure
plot([-1 1],[0,0],'linewidth',5,'Color','y') %creating a support
axis([-2 2 -5 1]) %constraining the axis
line([X X1],[Y Y1],'linewidth',2,'color','b') %creating a thread or a string
hold on
plot(X,Y,'O','MarkerSize',4,'markerfacecolor','g') %connecting a hook
plot(X1,Y1,'O','MarkerSize',20,'markerfacecolor','r') %creating a bob
title('Simple Pendulum')
legend('support','thread','hook','pendulum bob')
hold off
M(ct)=getframe(gcf)
ct=ct+1;
end
% saving the animation video
movie(M)
videofile=VideoWriter('pendulum.avi','Uncompressed AVI')
open(videofile)
writeVideo(videofile,M)
close(videofile)
Link for animation video:
https://drive.google.com/file/d/1vTwHD9nvmofYrlEMH9By5A60_IeZQ019/view?usp=sharing