Week 3 - Solving second order ODEs
% FUNCTION CODE
function [dthetha_dt] = ode_func(t,theta,b,g,l,m)
% Putting values of angular displacement
theta1=theta(1);
% Putting values of angular velocity
theta2=theta(2);
% Splitting 2nd order ODE
dtheta1_dt=theta2;
dtheta2_dt=-(b/m)*theta2-(g/l)*sin(theta1);
% Putting the values in variable
dthetha_dt=[dtheta1_dt ; dtheta2_dt];
end
%CODES
clear all
close all
clc
% Codes for pendulum motion
% Inputs
% damping coeff
b=0.05;
% gravity in m/s2,
g=9.81;
% length of the pendulum in m
l=1;
% mass of the ball in kg
m=1;
% initial conditions
theta_0=[0;3];
% time
t_span=linspace(0,20,300);
% Solve ODE using ode45
[t,results]=ode45(@(t,theta) ode_func(t,theta,b,g,l,m),t_span,theta_0);
% Plotting Angular displacement and Angular velocity.
hold on
% Angular displacement
plot(t,results(:,1),'Color','r')
% Angular velocity
plot(t,results(:,2),'Color','b')
xlabel('Time')
ylabel('Plot')
ct=1;
for i=1:length(t)
% Coordinates of pendulum with respect to angular displacement
x0=0;
y0=0;
x1=l*sin(results(i,1))
y1=-l*cos(results(i,1))
% Plotting the pendulum movement.
figure(2)
plot([x0,x1],[y0,y1])
hold on
plot([-1.5 1.5],[0 0],'color','r','LineWidth',3)
axis([-1.5 1.5 -1.5 0.5])
plot(x1,y1,'o','MarkerSize',20)
pause(0.0001)
hold off
% Capturing the frames
M(ct)=getframe(gcf);
ct=ct+1;
end
% Creating a video file
movie(M)
Videofile=VideoWriter('sec_order_ODE.avi','Uncompressed AVI')
open(Videofile)
writeVideo(Videofile,M)
close(Videofile)
% YOUTUBE LINK
%OUTPUT FIGURE
1)

2)

%EXPLANATION OF CODE
%FUNCTION CODE
Line1: A function of name ode_func is made using function command
Line3: Putting values of angular displacement
Line4: Putting values of angular velocity
etc
%CODES
Line2: close all = closes all the Plots.
Line3: clear all = clears all the variables in the workspace.
Line4: clc = clears the command window.
Line6 to 10: Inputs.
Line19: Using ode45 command
Line44: Plotting has started.
Line58: Creating Videofile
etc
% SHOWING ERRORS FACED AND SOLUTIONS USING SCREENSHOTS.
1)BASIC SPELLING MISTAKES
(SOLVED BY GOING THOROUGHLY WITH THE CODES)
2)BRACKET MISTAKES
(SOLVED BY GOING THOROUGHLY WITH THE CODES)
3)NOT USING END COMMAND
(SOLVED BY PUTTING IT IN RIGHT LINE)

4)PUTTING WRONG FUNCTION NAME IN THE CODE
(SOLVED BY CLEAR;Y GOING THROUGH IT)
