Week 3 - Solving second order ODEs
Solving second order ODEs: Write a program in Matlab that will simulate the pendulum motion.
Primary equation:
b = damping coefficient
m = mass of the bob
g = acceleration due to gravity
l = length of the string
Matlab Function :
%..........................................................................
%////////////////////////////////ODE\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
%..........................................................................
clear all
close all
clc
% Given data ~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-
b = 0.05; % Damping coefficient
g = 9.81; % Acc caused due to graviy
l = 1; % length in Metre
m = 1; % Mass in Kg
% Initial condition ~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~
tta = [0;5];
% Time points ~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~
T_span = linspace(0,20,500);
% Solve ODE ~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~
[t,results] = ode45(@(t,tta) ode_func(t, tta, b,g,l,m),T_span ,tta);
% Ploting ~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~
plot(t,results(:,1))
hold on
plot(t,results(:,2))
ylabel('Theta')
xlabel('time')
a = 1;
figure(2)
for i = 1:length(results(:,1))
theta0 = results(i,1);
x0=0;
y0=0;
x1=l*sin(theta0);
y1=-l*cos(theta0);
% plotting~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~--~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-
plot([-1,1],[0,0],'linewidth',5,'color','black');
line([x0,x1],[y0,y1],'linewidth',3)
hold on
plot(x1,y1,'o','markers',15,'markerfacecolor','g');
axis([-2 2 -1.5 0.5]);
pause(0.01);
M(a)=getframe(gcf);
hold off
a = a + 1;
end
% Making of the movie ~-~-~-~-~-~-~-~--~-~-~-~-~-~-~-~-~-~-~--~-~-~-~-~-~-~
movie(M)
videofile = VideoWriter('pendulum.avi','Uncompressed AVI');
open(videofile)
writeVideo(videofile,M)
close(videofile)
USER FUNCTION
%..........................................................................
%////////////////////////////////ODE FUNCTION\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
%..........................................................................
function [dtta_dt] = ode_func(t,tta,b,g,l,m)
tta1 = tta(1)
tta2 = tta(2)
dtta1_dt = tta2;
dtta2_dt = -(b/m)*tta2 - (g/l)*sin(tta1);
dtta_dt = [dtta1_dt; dtta2_dt];
end
Steps
1.first we use ' clear all ' ,'close all' , clc, to erase the previous in command. After that input values of Damping coefficient, Gravity, etc.
2.Now we the time from 0 to 20 sec and is given by linspace(0,20,500).
3.Next to solve the ODE by calling the matlab function ode_func(t, theta, b,g,l,m)
4.Next step is the different value of time and angel by using 'for loop'.
5. Last after plotting we need animation of the motion of the bob so we will use the movie command.
OUTPUT:
Error :
I can't able to get the animation which we want as per question.
which got solved by using "HOLD OFF"
which terminate the work of "HOLD ON"