Week 3 - Solving second order ODEs
Aim: To write a program that solves the equation of motion of a simple pendulum with damping.
Governing equation:
`(d^2theta)/dt^2`+`b/m*(d theta)/dt`+`g/l*sintheta` = 0
`b` = Damping coefficients
`m` = mass of bob
`g` = acceleration due to gravity
`l` = length of string
Main Code:
clear all
close all
clc
%Damping coefficients.
b = 0.05;
%acceleration due to gravity.
g = 9.81;
%length of string.
l = 1 ;
%mass of bob
m = 1 ;
%Time span
t_int = [0 20];
%Initial value of displacement and velocity.
theta_var = [0;3];
%ode45 Function calling.
[t,theta_1] = ode45(@(t,theta) ode_2(t,theta,b,g,l,m),t_int,theta_var);
%Assumed paramenters.
x0 = 0;
y0 = 0;
%Copying value of displacement from results to an array.
x1 = l*sin(theta_1(:,1));
y1 = -l*cos(theta_1(:,1));
%Arbitary value for array position to save video frame.
cap = 1;
for i = 1:length(x1)
plot(x0,y0)
plot([x0,x1(i)],[y0,y1(i)],'-o','markerfacecolor','r')
%To display thevalue of time in the movie.
text(0, -1.6,['Time = ',num2str(t(i,1))]);
axis([-2 2 -2 2])
%Saving each frame onto an array.
video(cap) = getframe(gcf);
%Incrementing the array position.
cap = cap+1;
end
%To open a Movie file.
movie(video)
%To save the movies in a specified format.
vf = VideoWriter('Pendulum.avi','uncompressed AVI');
open(vf);
%To write the frames saved to the movie file.
writeVideo(vf,video);
close(vf);
Function code:
function [dtheta_dt] = ode_2(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
- The main code starts with the process of assigning the values of length & mass of pendulum, damping coefficient and finally the acceleration due to gravity.
- Now the time span is defined.
- Here the initial displacement and velocity of the pendulum is defined.
- This step call the function which uses ode45 solver of the matlab to return the value of angular velocity and angular displacement.
[t,theta_1] = ode45(@(t,theta) ode_2(t,theta,b,g,l,m),t_int,theta_var);
- Here all the variables for solving are called
- t_int integrates the system of differential equation from initial to final value as provided in array with initial condition as provided in the array named theta_var.
- Now various points of movement of pendulum is traced by using subsequent formulas and the coordinates are then saved on to an array.
- Thus initial and various final points of pendulum are plotted and each frame is saved on to a file.
- This frames are combined and saved to specified format using the command 'writeVideo' and 'VideoWriter'.
Results:
Link for the video: https://drive.google.com/file/d/1MdMw5zNUWugbt8Qg36A_guLuHo2drbq6/view?usp=sharing
Conclusion:
The animation of the simple pendulum was successfully done and the link of the same has been uploaded.