Week 3 - Solving second order ODEs
clear all
close all
clc
%defining input variables
b= 0.05
g= 9.81
l= 1
m= 1
%intial condition i.e. position and velocity
theta_0= [0;3];
%time pionts
t_span= linspace(0,20,500);
%calling count for movie frames
ct=1;
%solve ODE
[t,results]= ode45(@(t,theta)ode_func(t,theta,b,g,l,m),t_span,theta_0);
%defining axis
O= [0 0];
axis(gca,'equal');
axis([-1.5 1.5 -1.5 0]);
grid on;
%defining loop for calling values from results
for i=1:length(t)
%end point of pendulum
p= l*[sin(results(i,1)) -cos(results(i,1))];
%base point
O_circ= viscircles(O,0.01);
%placing circle at the end point of pendulum
ball= viscircles(p,0.05);
%creating pendulum rod with line
pendrod= line([O(1) p(1)],[O(2) p(2)],'linewidth',2);
pause=0.003
%sequencing the frames
M(ct)= getframe(gcf);
ct = ct+1;
%deleting previous figures
if i<length(t)
delete(O_circ);
delete(ball);
delete(pendrod);
end
end
%creating video
movie(M)
videofile = VideoWriter('pend5.avi','uncompressed AVI');
open(videofile)
writeVideo(videofile,M)
close(videofile)
%ode_function
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
the code for simulating the pendulum motion is written above. first, the second-order differential equation was simplified and made function for it called ode_func. then it was called using inbuilt ode45 function. the output than used to plot different parts to assemble pendulum that includes rod and moving circle at the end. the movie was created using movie function using getframe. the trouble I got was that my video was not displaying any frames of pendulum except the end figure, later I figured it out by trying different things and got to know that this was due to placing of %sequencing of frames after the %deleting the previous figures.