Week 3 - Solving second order ODEs
CODE FOR SIMPLE PENDULUM ANIMATION:
clear all
close all
clc
%input variables
l=1;
m=1;
b=0.05;
g=-9.81;
%counter variable ct defined
ct=1;
% invoking ode 45 solver to solve the differential equation
[t_res,theta_res]=ode45(@(t,theta) dim(t,theta,b,g,l,m),[0,20],[0;3]);
%Initiating For loop for finding various positions of the other end of the rod at different times
for i=1:length(theta_res)
x=l*sin(theta_res(i,1));
y=-l*cos(theta_res(i,1));
%Using plot command to obtain 'Simple pendulum image'
plot([0,x],[0,y]);
hold on;
%Using another plot for placing circular Marker symbolizing the Bob
plot(x,y,'o','MarkerSize',20,'MarkerEdgeColor','red','MarkerFaceColor','red');
hold off
axis([-1,1,-1,1]);
title('simplependulum animation')
%Get frame comment
M(ct)=getframe(gcf);
ct=ct+1;
end
% Using Movie command to create Simple pendulum animation
movie(M)
videofile=VideoWriter('simple pendulum animation.avi','Uncompressed AVI');
open(videofile)
writeVideo(videofile,M)
close(videofile)
FUNCTION CODE REFERRED IN THE ABOVE CODE AS THE ARGUMENT TO ODE45 SOLVER:
function [thetaa]=dim(t,theta,b,g,l,m)
dtheta1_dt=theta(2);
dtheta2_dt=-(b/m)*dtheta1_dt+(g/l)*sin(theta(1));
thetaa=[dtheta1_dt;dtheta2_dt];
end
Explanation:
1)b,g,l,m are defined with the variables carrying their usual meaning
2)ODE 45 solver was used to solve the second order differential equation by converting this into 2 first order differential equations:
GENERAL SYNTAX:[TOUT,YOUT] = ode45(ODEFUN,TSPAN,Y0) where T out and Y out are values of independent and corresponding values of output variables respectively. Here, t_res and theta_res indicate the time and angular position and velocity array respectively.
3)A separate Function code was written by the name dim(t,theta,b,g,l,m) which returns 'thetaa' with two elements representing angular position and velocity of the link- and also to serve as argument of ODE45 solver in original code.
4)'For' loop was used to fix different positional configuration-the loop counter variable running from 1 to length(theta_res)- each representing a unique angular position during its motion.
5)Plot command with circular marker of size 20 and with colour red was used to represent the simple pendulum with bob during the motion.
6)Movie command was used to create an animation of the motion of simple pendulum and the file was named 'simple pendulum animation. The image collected by getframe commanded were grouped and written into this file by the command 'Write video'
ERROR ENCOUNTERED:
USED THETA1 TO ADDRESS FIRST COLUMN OF THETA INSTEAD OF THETA(1)
FORGOT TO INCLUDE '*' OPERATOR WHICH WAS LATER CORRECTED
GOOGLE DRIVE LINK OF ANIMATION VIDEO:
https://drive.google.com/file/d/1vJlHAi26qfIw_4iN4x90_ibX0Ymtgcku/view?usp=sharing