- Solving the second order ode to first order ode of a simple pendulum and to plot displacement, velocity vs time and to animate the motion of pendulum with given conditions.
clear all
close all
clc
% Given parameters
% Damping Coefiicient
b = 0.05;
% Gravitational constant (m/s^2)
g = 9.81;
%length of the pendulum (m)
l = 1;
% mass of the ball (kg)
m = 1;
% Initial conditions
theta_0 = [0 3];
t_span = linspace(0,20,300);
%solving ode- ode45 command is used to solve ode
[t, results] = ode45(@(t,theta) ode_func(t, theta,b,g,l,m),t_span,theta_0);
figure(1)
plot(t,results(:,1))
hold on
plot(t, results(:,2))
xlabel('Time')
ylabel('Plot')
% Annimation
result2 = results(:,1);
ct = 1;
for i = 1:length(result2)
position = result2(i);
x= 0;
y = 0;
x1 = l*sin(position);
y1 = -l*cos(position);
figure(2)
plot([x x1],[y y1],'-o','MarkerSize',15,'markerfacecolor','g','markeredgecolor', 'g','Linewidth',3)
axis([-2 2 -2 2])
hold on
plot([-1 1],[0 0],'Linewidth',5)
M(ct) = getframe(gcf);
hold off
ct = ct+1;
end
movie(M)
videofile = VideoWriter('solving_ode.avi','Uncompressed AVI');
open(videofile)
writeVideo(videofile,M)
close(Videofile)
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
- In the above program initial parameters are given such as damping coefficient, pendulum length and mass of the ball.
- time period is 0 to 20 and taken 300 values in between, given angular displacement = 0, angular velocity = 3 rad/sec at time t = 0 sec
- using the ode45 command to solve ode, convert second order ode to first order ode by creating a function using function command, we obtain main components time t and angular displacement theta.
- plot command is used to plot velocity and displacement on y-axis and time on x-axis.
- using for loop we have obtained the position at different time and it is plotted.
- Movie command is used to create an annimation and marker command to create sphere.
https://youtu.be/SrbClC-aTQ8