Week 3 - Solving second order ODEs
Code with comments:
clear all
close all
clc
% inputs
b = 0.05 % Damping coefficient
g = 9.81 % gravity
l = 1 % length of pendulum
m = 0.1 % mass
% initial condition
theta_0 = [0;5]
% time points
t_span = linspace(0,10,500);
% solve ode
[t, results] = ode45(@(t,theta) ode_45(t, theta, b,g,l,m),t_span,theta_0);
%Fiures and plot
plot(t,results(:,1))
hold on
plot(t,results(:,2))
xlabel('plot')
ylabel('time')
% for loop for generating animation video
a = results(:,1)
ct = 1; % Counter
for i=1:length(a);
x=0;
y=0;
x1=l*sin(a(i))
y1=l*cos(a(i))
figure(2)
plot ([x x1],[y -y1])
hold on
plot (x1,-y1,'.','markersize',20)
hold off
axis ([-2 2 -2 2])
pause (0.1)
% Array to store the inputs of figure
M(ct) = getframe(figure(2));
ct = ct+1;
end
% Movie
movie(M)
videofile = VideoWriter('ODE_avi.avi','Uncompressed AVI')
open(videofile)
writeVideo(videofile,M)
close(videofile)
ode_45 function code:
function [dtheta_dt] = ode_45 (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
Output:

Animation Video:
https://drive.google.com/file/d/1f7TzhwcwvSbhRZBE8Yoh28FHNB20LPNv/view?usp=sharing
Errors:
1.) The time array was not defined properly.
originally used array:
t_span = (0,10,500)
desired array:
t_span = linspace (0,10,500)

2.) Code was not generating output:
The function of ode_45 was called from another file whose name was not the same as it was defined in the main code.
In the main code, the function called was ode_func whereas the file was saved as ode_45, so it was giving an error.



3.) The getframes command was not spelt properly
