Week 3 - Solving second order ODEs
Aim : Write a program to simulate the transient behaviour of a simple pendulum and to create an animation of it's motion.
Governing Equation :
second order differential equation
`(d^2 θ)/(dt^2 ) +b/m (dθ)/dt +g/l(sinθ)=0`
where,
g = gravity in m/s2,
L = length of the pendulum in m,
m = mass of the ball in kg,
b=damping coefficient.
Objective :
- write a program that solves the simple pendulam ODE.
- plot the animation of simple pendulum.
Steps of code :
- write a function code so that we can check any value of influencing parameter
- start coding main program with close all clear all clc.
- define the inbput parameters fpor the equation
- define the condition for displacement and velocity
- then call the function solve with ode45
- plot the graph
- to obtain the pendulum motion use the loop . define the loop to get different value
- plot bob by marker command and pendulum roop
- for animation use getframe video write movie command
code:
function
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];
endmain code
close all
clear all
clc
% Inputs
b = 0.05;
g = 9.81;
l = 1;
m = 1;
% initial condition
theta_0 = [0;3];
% TIME POINT
t_span = linspace(0,20,200);
% solve ode
[t,results] = ode45(@(t,theta) ode_func(t,theta,b,g,l,m),t_span,theta_0);
figure(1)
hold on
plot(t,results(:,1))
plot (t,results(:,2))
ylabel('plot')
xlabel('time')
% animation
figure(2)
ct = 1;
for i = 1:length(t_span)
x0 = 0;
y0 = 0;
x1 = l*sin(results(i,1));
y1 = -l*cos(results(i,1));
% ploting horizontal line
plot([-1 1],[0 0],'linewidth',3,"Color",'k')
hold on
% ploting the rope
plot([x0 x1],[y0 y1],'linewidth',3,'Color','r')
hold on
%ploting bob
plot(x1,y1,'o','markerfacecolor','b','markersize',10)
grid on
axis([-2 2 -2 2])
pause(0.005)
hold off
M(ct) = getframe(gcf);
ct = ct+1;
end
movie(M)
videofile = VideoWriter('o.avi','Uncompressed avi');
open(videofile)
writeVideo(videofile,M)
close(videofile)
Result:
graph
screenshot of output
Animation youtube link :
https://www.youtube.com/watch?v=rJlYQEcUTPI
Conclusion:
written program to simulate the behavior of simple pendulum amd created the animation