Week 3 - Solving second order ODEs
clear all
close all
clc
%damping coefficient
b = 0.05
%length of the pendulum in mm
l = 1
%mass of the ball in kg
m = 1
%gravity in m/s^2
g = 9.81
%initial condition
theta_0 = [0;3];
%time points
t_span = linspace(0,20,200);
% solve ode
[t,results] = ode45(@(t,theta)ode_func(t,theta,b,l,m,g),t_span,theta_0);
figure(1)
plot(t,results(:,1))
hold on
plot(t,results(:,2))
xlabel('time')
ylabel('plot')
legend('displacement','velocity')
%inputs
ct = 1
for i = 1:length(t_span)
x0 = 0;
y0 = 0;
x1 = l*sin(results(i,1));
y1 = -l*cos(results(i,1));
%plotting
figure(2)
plot([x0 x1],[y0 y1],'color','b','LineWidth',3)
hold on
plot(x1,y1,'o','markersize',15,'MarkerFaceColor','g')
axis([-2 2 -2 2])
hold off
M(ct) = getframe(gcf);
ct = ct + 1 ;
end
% animation of the simple pendulum
movie(M)
Videofile = VideoWriter('simple_pendulum.avi','Uncompressed AVI')
open(Videofile)
writeVideo(Videofile,M)
close(Videofile)
Explanation of the code-
While solving higher order ODE we need to break down in to the first order ODE. Gave the inputs as a 'b' is a damping coefficient and 'g' is a gravity and L is the length of the pendulum, 'm' is the mass. While solving a 1st ODE, initial condition for the displacement of pendulum is zero and velocity is 3 m/s. t-span is an time array it goes to ( 0 to 20 sec) in 200 values in between.
ODE45 is inbuilt solver in the matlab. ode is a function of t and theta and this dependant and independant variables of our ode system. then defined the ode_function followed by b,g,L,m after that we provide the initial conditions time array and theta. Plotted the displacement and velocity diagram by using plot command in figure1. Used the legend command for the indication of displacement and velocity seperately. then created a for loop for the simulation of simple pendulum.then defined the values of x0 y0 x1 y1 plotted accordingly by using plot command then used 'Marker' command in matlab to specify the pendulum also gave the marker face color and the markersize.then defined the axis then gave input ct=1, ct refers to the each and every frame, by using getframe command get the current figure and then end the loop.
To do the simulation created movie then created videofile by using Videowriter command ' simple_pendulum.avi', openvideofile,writevideofile, closevideofile used accordingly.successfuly got the simulation of simple pendulum by using matlab.
Errors occured in the solving challenge but errors resolved by taking help of support engineer.screenshots are attached below.
ode_func.m
function [dtheta_dt] = ode_func(t,theta,b,l,m,g)
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