Week 4.1 - Solving second order ODEs
creating function name ode_func :-
%defining function for ODE
function [dtheta_dt] = ode_func(t,theta,b,g,l,m)
% defining theta1 & theta2
theta1 = theta(1);
theta2 = theta(2);
%1st ODE
dtheta1_dt=theta2;
%2nd ODE
dtheta2_dt=-(b/m)*theta2-(g/l)*sin(theta1);
%combining theta & theta2
dtheta_dt=[dtheta1_dt;dtheta2_dt];
end
Main Code :-
clear all
close all
clc
% Input variables for simple pendulum
b=0.05; %damping coefficient.
g=9.81; % acceleration due to gravity m/s^2
l=1; % length of pendulum in m
m=1; %mass of the ball in kg,
%initial condition fo displacement and velocity
theta_0=[0;3];
%time points arrey
t_span = linspace(0,20,500);
%solve ODE
%ODE45 is the inbuilt command, t & theta is the main input of ode45 comand
%it is the function of t & theta
%ode_func is the function created having input of t,theta,b,g,l,m.
% & t_span is the time arrey & theta_0 is the initial condition
[t,results]=ode45(@(t,theta) ode_func(t,theta,b,g,l,m),t_span,theta_0);
%plot between the time and results, results is the column vwctor having two
%column 1st is displacement and 2nd is velociti
plot(t,results(:,1)) % plot between time and displacement
hold on
plot(t,results(:,2)) % plot between time and velocity
xlabel('time')
ylabel('plot')
figure(2)
ct=1;
% craeting a loop for changing position of the pendulum throug different
% dispalcement over length of t_span
for i=1:length(results(:,1))
x0=0;
y0=0;
x1=l*sin(results(i,1));
y1=-l*cos(results(i,1)); % neagtive sign indiacate that the y1 is alwase negative as it is in the 3rd & 4th quadrant
% ploting the horizontal line
plot([-1.5 1.5],[0 0],'linewidth',2)
hold on
%ploting the length of of pendulum
plot([x0 x1],[y0 y1],'linewidth',3,'color','b')
%ploting the sphear of size 20
plot(x1,y1,'o','markersize',20,'Color','r')
% giving axis limits
axis([-1.5 1.5 -1.5 1.5])
%giving a pause between changing position
pause(0.001)
% for creating a movie using command frame
M(ct) = getframe(gcf);
hold off
% incremenat counter
ct=ct+1;
end
%create a movie file
movie(M)
videofile = VideoWriter('simple_pendulum.avi')
%opening a video file
open(videofile)
%writing a video into file
writeVideo(videofile,M)
%close video
close(videofile)
Output is attached as video file please find