Week 3 - Solving second order ODEs
AIM: TO WRITE A PROGRAM THAT WILL SIMULATE A SIMPLE PENDULUM AS SHOWN IN QUESTION
%% solving 2nd order ODE
clear all
close all
clc
b=0.05; %damping coefficient
g=9.81; %acceleration due to gravity
l=1; %length of the pendulum
m=1; % mass of the pendulum
%initial condition
theta_0=[0;3];
%time input
t_span=linspace(0,20,300);
%ode solver
[t,results] = ode45(@(t,theta) ode_func( t, theta, b, g, l, m), t_span, theta_0);
plot(t,results(:,1),'color','b','linewidth',1.5);
hold on
plot(t,results(:,2),'color','r','linewidth',1.5)
legend('displacement','velocity');
xlabel('time(sec)');
ylabel('angular displacement and angular velocity');
grid on;
%% creating an animation of pendulum
ct=1;
for i= 1:length(results(:,1))
x_0 = 0;
y_0=0;
x_1= l*sind(results(i,1));
y_1= -(l*cosd(results(i,1)));
figure(2);
plot([x_0 x_1], [y_0 y_1],[-0.5 0.5],[0 0],'color','b','linewidth',1);
hold on
plot(x_1, y_1, 'marker','o','markerfacecolor','r','markersize',6)
axis([-0.75 0.75 -1.5 0.5])
title ('animation of pendulum')
hold off
grid on
M(ct)=getframe(gcf); % getting frames
ct=ct+1;
end
% creating movie
%creating a movie of the 2_R_robotic arm
movie(M)
videofile = VideoWriter('pendulum.avi','MPEG-4');
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/g)*theta2 -(g/l)*sin(theta1);
dtheta_dt=[dtheta1_dt;dtheta2_dt];
end
NO ERRORS HAVE BEEN FOUND WHILE EXECUTING THE PROGRAM