Week 3 - Solving second order ODEs
https://www.youtube.com/watch?v=US5Sd4RZlhw
b=0.05; %damping coefficient
g=9.81; %gravity in m/s2
m=1; %mass of the ball in kg
l=1; %length of pendulum in m
%initial conditions
theta_0=[0;3];
%time points
t_span=linspace(0,20,300);
%solving ODE
[t,results]=ode45(@(t,theta) ode_fun(t,theta,b,g,l,m),t_span,theta_0);
%plotting
ct=1;
for i=1:length(t)
%initial point or fixed point
x0=0;
y0=0;
%calculation of second point
x1=l*sin(results(i,1));
y1=-(l*cos(results(i,1)));
figure(1)
plot([-0.5 0.5],[0 0],'linewidth',5,'color','b')
axis([-2 2 -2 2])
hold on
plot([x0 x1],[y0 y1],'linewidth',2,'color','r')
plot(x1,y1,'o','markersize',20,'markerfacecolor','g','markeredgecolor','b')
pause(0.03)
hold off
Ani(ct)=getframe(gcf);
ct=ct+1;
end
%creating animation
movie(Ani)
videofile=VideoWriter('Pendulum_animation.avi','Uncompressed AVI');
open(videofile)
writeVideo(videofile,Ani)
close(videofile)
%plotting of angular velocity and displacement with respect to time
figure(2)
plot(t,results(:,1),'color','r')
hold on
plot(t,results(:,2),'color','g')
xlabel('Time')
ylabel('Angular velocity and Displacement')
% code for the function
function [dtheta_dt]=ode_fun(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