Week 3 - Solving second order ODEs
% Solving second order ODEs simulation of transient behavior of a simple pendulum using MATLAB
clear all
close all
clc
% inputs
b=0.05; % b = Damping co-efficient of resistant in Ns/m
g=9.81; % g = Acceleration due to gravity m/s^2
l=1; % l = Length of pendulum in m
m=1; % m = Mass of pendulum in kg
% theta = Angle of pendulum in rad
% INITIAL CONDITION
theta_0=[0,3]; % theta = 0, Angular velocity = 3 rad/s
% Time span of simulation
t_span = linspace(1,20,500);
%Solving 2nd order ODE using ode45 MATLAB function
[t, results]=ode45(@(t,theta) ode_funcc(t,theta,b,g,l,m),t_span,theta_0);
% Plotting
figure(1)
grid on
hold on
plot(t,results(:,1));
plot(t,results(:,2));
hold off
title('Simple Pendulum with Damping')
xlabel('Time t in s')
legend('Angular Position in degrees','Angular Velocity in rad/s')
% converting angular position into x,y coordinate points
X = sin(results(:,1)).*-l;
Y = cos(results(:,1)).*-l;
[~, totalTime] = size(t_span);
% Creating animation of simple pendulum motion
for i = 1:totalTime
labelStr1 = strcat(texlabel('theta'),' = ',sprintf('%0.2f',results(i,1).*(180/pi)),' degrees');
labelStr2 = strcat(texlabel('omega'),' = ',sprintf('%0.2f',results(i,2)),' rad/s');
f=figure(2);
hold on
plot([0 X(i,1)],[0 Y(i,1)],'linewidth',3,'marker','o','markerfacecolor','black');
plot(X(i,1),Y(i,1),'o','MarkerFaceColor','r','MarkerSize',20)
%text(X(i,1),Y(i,1),labelStr1,'VerticalAlignment','bottom','HorizontalAlignment','left');
%text(X(i,1),Y(i,1),labelStr2,'VerticalAlignment','top','HorizontalAlignment','left');
%if i ~= totalTime
%quiver(X(i,1),Y(i,1),X(i+1,1)-X(i,1),Y(i+1,1)-Y(i,1),5,'m','LineWidth',2)
%end
annotationStr = strcat('Time t = ',sprintf('%0.2f',t(i,1)),' seconds');
annotation('textbox',[0.5 0.5 0.1 0.1],'string',annotationStr,'FitBoxToText','on');
axis([-1 1.5 -1.5 0.5])
title('Simulation of Simple Pendulum with Damping')
xlabel('x axis in m')
ylabel('y axis in m')
%pause(0.001)
M(i) = getframe(gcf);
if i ~= totalTime
clf(f,'reset')
end
end
movie(M);
videofile = VideoWriter('pendulum','Uncompressed AVI');
open(videofile);
writeVideo(videofile,M);
close(videofile);