Week 4.1 - Solving second order ODEs
clear
close
clc
%inputs damping coefficient,length,mass,gravity
b = 0.05;
l = 1;
m = 1;
g = 9.81;
ct = 1;
%intial condition - initial displacement and velocity
theta_0 = [0;3];
%time points from 0 to 20 seconds
%to make the pendulum swing as asked, I have taken t_span from 20 to -20
t_span = linspace(20,-20,400);
%solve ODE
[t,r] = ode45(@(t,theta)ode_function_pendulum(t,theta,b,l,m,g),t_span,theta_0);
for i = 1:length(t_span)
A = t_span(i);
x0 = 0;
y0 = 0;
x1 = -l*sind(A);
y1 = -l*cosd(A);
figure(1)
%plotting x0,y0 fixed position
plot(x0,y0,'*','color','g')
%using hold on command to represent all plots in one
hold on
%plotting pendulum ball in red color with size 20
plot(x1,y1,'marker','O','markerfacecolor','r','markersize',20)
%plotting pendulumm string(length) in blue color with width 2
plot([x0 x1],[y0 y1],'linewidth',2,'color','b')
%using hold off command for smooth flow of the plot
hold off
axis([-0.5 0.5 -1.2 0.2])
xlabel('displacement')
ylabel('length of pendulum')
title('second order ODE')
%to show all the frames in one single file
D(ct) = getframe(gcf);
ct = ct+1;
end
%creating a movie to store the video for result
movie(D)
videofile = VideoWriter('ordinary_differential_equation_2nd_order.avi','Uncompressed AVI');
open(videofile)
writeVideo(videofile,D)
close(videofile)
I have used the input values as mentioned in the question above and I have tried it with the values instructed in the live class and felt these values gave a smoother flow video. I have used -20 to 20 as t_span limits(400 values) to present oscillation of pendulum from left to right.
here I have used for loop to create 400 intervals inbetween -20 and 20 which gnerates different values of x,y by calculating the equations of x,y.
ODE_FUNCTION_PENDULUM
%writing a function for second order differential equation using ode_function
function [dtheta_dt] = ode_function_pendulum(t,theta,b,l,m,g)
%converting the second order DE into first order DE
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
ode func is an inbuilt function which solves the differential equations. here in this function I have modified the 2nd order DE into 1st order DE for the ode function to solve easily.
google drive link for pendulum movie:
https://drive.google.com/file/d/1IwGE29LzvUWvSOKKGZeDpFF-QB2p7_oY/view?usp=sharing