Solving second order ODEs (MATLAB)
AIM:
objective is to write a program that solves the given ODE. This ODE represents the equation of motion of a simple pendulum with damping
governing equations:
CODE:
the following functions are used in this code
ode45- this is a preexisting MATLAB solver that is used to solve second order differential equations using the range kutta method. we need to create a function that defines the given 2nd order ode, this function is then passed on to the solver along with the time and the initial conditions. it returns the results as an array and the time array
clear all
close all
clc
b=0.05;
g=9.81;
l=1;
m=1;
% initial conditions
theta_0=[0;3];
t_span=linspace(0,20,500);
%solve ode
[t,result]=ode45(@(t,theta) ode_func(t,theta,b,g,l,m),t_span,theta_0);
figure(1)
plot(t,result(:,1))
hold on
plot(t,result(:,2))
xlabel('plot')
ylabel('time')
f=1;
for i=1:length(t)
%initial position
x=0;
y=0;
%final position
x1 = l*sin(result(i,1));
y1 = -l*cos(result(i,1));
%plotting
figure(2)
plot([-1,1],[0,0],'linewidth',5,'color','r') %for the base line
hold on
plot([x,x1],[y,y1],'linewidth',5,'color','b') %for the pendulum line
plot(x1,y1,'o','markers',20,'markerfacecolor','b') %for the pendulum ball
grid on
axis([-2 2 -2 1])
pause (0.03)
M(f)= getframe()
f=f+1;
hold off
end
movie(M) % to play the array of frames in 'm' as animation
%to create a video file of the animation
videofile= VideoWriter('Pendulum.avi','Uncompressed AVI' );
open(videofile)
writeVideo(videofile,M)
close(videofile)
the function ode_func is defined as shown below
%the ode_func function
function[dtheta_dt]= ode_func(t,theta,b,g,l,m)
% b=0.05;
% g=9.81;
% l=1;
% m=0.1;
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
Results:
the video was generated as shown in the link given, the graph of the velocity vs displacement is attached below
video link:https: //drive.google.com/file/d/1CBmWd8nvKwoZn-FzyzrJJj2h2K0u8gNm/view?usp=sharing