Pendulum's motion using matlab
AIM
To create a video of pendulum's motion with damping.
THEORY
To create the path follow by pendulum, we must solve the ordinary differential equation of pendulum.The eqn. is
where
- theta is angle made by bob with vertical.
- b is damping constant.
- t is time interval
- g is acceleration due to gravity
- l is length of string.
OBJECTIVE
To solve ODEs of pendulum's motion and create video.
BODY
Codes
Main Code
clc;
clear all;
close all;
%input
b=0.05; %b-damping coefficient
l=1; %l-length of string
m=1; %m-mass of pendulum
g=9.81;% g-acceleration due to gravity
%time interval and initial value
ts= linspace(0,20,400);
theta0=[0;3];
%solution of differential eqn.
[t,out]=ode45(@(t,theta) func(t,theta,b,l,m,g),ts, theta0);
%plotting
figure(1)
plot(t,out(:,1),t,out(:,2))
xlabel('time ts');
ylabel('velocity or acceleration')
title('velocity and acceleration of pendulum with damping');
% For animation
%input as origin or fixed position of pendulum
x0=0;y0=0;
%deriving angle from solved ODEs
angle=asin((l/g).*(-out(:,2)-(b/m).*out(:,1)));
%calculating coordinates of bob at given angle
y=-l.*cos(angle);
x=l.*sin(angle);
%plotting of coordinates with fixed point
figure(2)
for i=1:400
plot([x0 x(i)],[y0 y(i)],'-c',x(i),y(i),'ro','MarkerFaceColor','r','MarkerSize',13,'MarkerEdgeColor','k');
pause(0.001)
axis([-1 1 -1.3 0])
p(i)=getframe(gcf);
end
%creating animation
movie(p);
vf=VideoWriter('ode_pendulum.avi','Uncompressed AVI');
open(vf);
writeVideo(vf,p);
close(vf)
Function
function [ode]=func(t,theta,b,l,m,g)
dtheta1=theta(2); %dtheta1 = 1st derivative of theta w.r.t time
dtheta2=-(b/m)*dtheta1-(g/l)*theta(1); %%dtheta2 = 2st derivative of theta w.r.t time
ode=[dtheta1;dtheta2];
end
saved as func.m.
OUTPUT
Animation link-https://www.youtube.com/watch?v=ub-8Czxgojk
EXPLANATION
In the code I used function called func to solve differential equation. I stored the result in out variable. Then to create animation, I derive theta from the differential eqn. by putting the values of out variables. After getting the angle I used the basic trignometry to get the coordinate of bob.Then I use for loop to plot every coordinate with fixed coordinate and at bob I use the plot with marker command to get shape of bob. After getting all the plot I stored it into array called p using getframe command and pause command.For animation, I use the movie command.