Week 3 - Solving second order ODEs
Assignment Pendulum:
The objective is to write a program that solves the following ODE. This ODE represents the equation of motion of a simple pendulum with damping.
A program in MATLAB that will simulate the pendulum motion
use,
L=1 meter,
m=1 kg,
b=0.05.
g=9.81 m/s2.
Simulated the motion between 0-20 sec, for angular displacement=0, angular velocity=3 rad/sec at time t=0.
Firstly, the input parameters are written in the code, and the ODE is split into two first-order ODE’s and is then solved using ode45, an inbuilt solver in MATLAB.
The code is
clear all
close all
clc
% pendulum parameters
b=0.05;
g=9.81;
l=1;
m=1;
% initial conditions
theta_0 = [0;3];
% time span
t_span = linspace(0,15,500);
% solving ode
[t,results] = ode45(@(t,theta) fun_pen(t,theta,b,g,l,m),t_span, theta_0);
figure(1)
plot(t,results(:,1)); % plotting the results
hold on
plot(t,results(:,2));
xlabel('time')
ylabel('Angular displacement vs Angular velocity')
legend('Angular displacement','angular velocity')
hold off
grid on
% defining origin
figure(2)
O = [0, 0];
axis(gca,'equal'); % defining aspect ratio
axis([-1.5 1.5 -1.5 0.5]);
grid on;
ct =1; % for capturing
for i = 1:length(t_span)
% various coordinates
P = l*[sin(results(i,1)) -cos(results(i,1))];
O_circles = viscircles(O,0.01);
Pend = line([O(1) P(1)],[O(2) P(2)]);
ball = viscircles(P,0.05);
pause(0.01)
M(ct) = getframe(gcf);
ct = ct+1;
if i<length(t_span)
% deleting the previous captured images
delete(Pend);
delete(ball);
delete(O_circles);
end
end
% creating movie
movie(M)
Videofile = VideoWriter('pendulam_video_final.avi','Uncompressed AVI');
open(Videofile);
writeVideo(Videofile,M);
close(Videofile);
This is the main function which is used to solve the ode.
1st the input conditions are mentioned for the pendulum along with initial conditions. Then the ode solver is solved using anonymous function. After that the graphs are plotted for angular displacement and velocity. Then code for plotting pendulum is written and then for movie making.
For the function the 2nd order ode is broken down into two 1st order odes and then solved. To make it more generalised various parameters are given as input so that we can vary them and see the behaviour of the pendulum.
The anonymous function written for the solver is below
function [dtheta_dt]= fun_pen(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
Figure 1 Angular Displacement and VelocityThe following were the errors
The following were the errors:
1. The mistake in ode fun line- I had made a couple of mistakes at this stage viz- I forgot to add semicolon in theta, and I wrote theta_zero instead of theta_o.
2. Error in graphs plotted- I forgot to add hold off command after the 1st graph.
3. The coordinates were not proper in the plotting command of the pendulum
the plots is
the video link is https://youtu.be/1DO6z1tZUF0