Week 3 - Solving second order ODEs
Main program
%Solving second order ODE
close all
clear all
clc
%Inputs
b= 0.05; %Damping co-efficient;
g= 9.81; %Gravity (m/s^2);
l= 1; %Length (m);
m= 1; %Mass (kg);
%Initial condition
theta_0=[0;3];
%Time points
t_span= linspace(0,20,500);
%Solve ode
[t, results] = ode45(@(t, theta) ode_func(t, theta, b, g, l, m), t_span, theta_0);
plot(t, results(:,1))
hold on
plot (t, results(:,2))
ylabel('Plot')
xlabel('Time')
legend('Angular displacement', 'Angular velocity')
title('Angular displacement vs Angular velocity')
ct=1;
theta2=results(:,1);
for i=1:length(theta2)
theta=theta2(i);
x0=0;
y0=0;
x1= l*sin(theta);
y1= -l*cos(theta);
%Plot
figure(2)
plot([-1 1],[0 0],"color","k","linewidth",3)
hold on
plot([x0 x1],[y0 y1],'color','m')
plot(x1,y1,'o','markers',10,'markerfacecolor','b')
hold off;
grid on;
title('Pendulum displacement')
axis([-1 1 -1.5 0.5])
pause(0.01)
hold off
M(ct)= getframe(gcf);
ct=ct+1;
end
movie(M)
videofile = VideoWriter('Pendulum_displacement','Uncompressed AVI');
open(videofile)
writeVideo(videofile,M)
close(videofile)
Function
%Function code for ode
function [dtheta_dt] = ode_func(t, theta, b, g, l, m)
theta1=theta(1);
theta2=theta(2);
dtheta1_dt= theta2;
dtheta2_dt= -(b/l)*theta2-(g/l)*sin(theta1);
dtheta_dt = [dtheta1_dt; dtheta2_dt]
end
Report
Step-wise explanation of your code.
- Basic inputs like close all clear all clc.
- Giving inputs or known data.
- Giving a function name and defining the function or formula.
- Plotting the graphs accordingly with desired labels.
Mention the errors faced while programming.
- Incorrect dimensions of matrix.
- Missed element wise operator and paranthesis.
- Typographical errors.
- Plotting of pendulum displacement in graph was difficult.
Steps taken to overcome those errors.
- By providing the element wise operator.
- Correct use of paranthesis and brackets.
- Practising to avoid typographical errors.
- Took help of Sai from skill-lync to get correct understanding of ODE function and inputs.
Youtube video link for Pendulum displacement video
https://youtu.be/hyuYh3tz2fY