Week 3 - Solving second order ODEs
Main code to Solve ODE
%input variables to solve the pendulum equation
b=0.05;
g=9.81;
l=1;
m=1;
%input initial conditions of displacement and velocity
theta_v = [0 3];
%time intervals at which values of disp and vel are found out
t_span=linspace(0,20,100);
%To Solve ODE
[t,results] = ode45(@(t,theta)ode_func(t,theta,b,g,l,m),t_span,theta_v);
disp=results(:,1);
ct=1;
for i= length(disp)
position = disp(i);
x0=0;
y0=0;
x1=1*sind(position);
y1=-1*cosd(position);
plot([x0 x1],[y0 y1],x1,y1,'g.','markersize',20,'linewidth',2);
axis ([-2 2 -2 2]);
hold off
grid on
M(ct)=getframe(gcf);
ct = ct+1;
end
%Animation
movie(M)
videofile= VideoWriter('Pendulum');
open (videofile)
writeVideo(videofile,M)
close(videofile)
%to plot graph
plot(t,results(:,1));
hold on
plot(t,results(:,2));
hold off
xlabel('time');
legend('Displacment with time','velocity with time');
Function Code for ODE
function [dthetadt] = ode_func(~,theta,b,g,l,m)
theta1=theta(1);
theta2=theta(2);
dtheta1dt=theta2;
dtheta2dt=-(b/m)*theta2-(g/l)*sind(theta1);
dthetadt=[dtheta1dt;dtheta2dt];
end
Screenshot of Output

