Week 3 - Solving second order ODEs
main code :
clear all
close all
clc
m = 1;
b = 0.05;
g = 9.81;
l = 1;
%Initial Conditions
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)
y = results(:,1);
plot(t,y)
hold on
plot(t,results(:,2))
xlabel('time')
ylabel('plot')
ct = 1;
for i = 1:length(y)
x0 = 0;
y0 = 0;
y1 = -l*cos(y(i));
x1 = l*sin(y(i));
plot([x0 x1],[y0 y1],'linewidth',4);
hold on
plot(x1,y1,'o','markersize',20,'color','r')
hold on
plot([-2 2],[0,0],'linewidth',5,'color','y')
axis([-2,2,-2,2])
pause(0.01)
M(ct)= getframe(gcf)
hold off
ct = ct+1
end
movie(M)
videofile = VideoWriter('Pendulum Animation.avi');
open(videofile)
writeVideo(videofile,M)
close(videofile)
function code :
function [dtheta_dt] = ode_func(t,theta,b,g,l,m)
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
youtube video link for the pendulum animation :
report : (inserted below)