Week 3 - Solving second order ODEs
follow the working code:
clear all
close all
clc
b=0.05; %damping coeficient
g=9.81; %gravity
l=1; %lenght of pendulum
m=1; %mass
%initial condition
theta_0 = [0,5];%initial displacement is 0 ,and initial velocity is 3rad/s
%time points
tspan = linspace(0,100,500);% time go from 0 to 10 seconds with 500 values
% solve ODE
[t, results] = ode45(@(t,theta) ode_func(t,theta,b,g,l,m),tspan, theta_0);
%comments
%ode45 - is a comand used to integrates the system of differential equations
%(@(t,theta)defining main inputs are t and theta
%odefunc(t,theta,b,g,l,m) defining our funciton
% t_span initial condition, intagration and the time aray
thetam=(results(:,1))
ct=1
for i = 1:length(thetam)%defining loop
thetham2=thetam(i)
x0 = 0;%defining x0 variable
y0 = 0;%defining y0 variable
x1 = -l*cos(thetham2);%defining the x1 position based on theta position
y1 = -l*sin(thetham2);%defining the y1 position based on theta position
figure(1)%take a figure in state moment
plot([y0 y1],[x0 x1])%ploting the x and y position in the actual moment
hold on % holding the plot
plot(y1,x1,'o','markers',10)%adding a marker as pendule mass
hold off%holding off the plot
axis([-2 2 -2 2])%defining axis
pause(0.03)%pausing time before continue the loop
M(ct) = getframe(gcf)%geting the frames
ct=ct+1 % increment the counter
end
movie(M)%generate a movie with all frames saved
videofile = VideoWriter('pendule_2','Uncompressed AVI')%create a videofile
open(videofile)%acess the videofile
writeVideo(videofile,M)%write the frames inside the videofile
close(videofile)%close videofile
follow the 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/m)*theta2 -(g/l)*sin(theta1);
dtheta_dt = [dtheta1_dt; dtheta2_dt];
end
In the process I made some mistakes:
first I did not understand how to calculate the pendule position so I was trying to use the acos once I think the results(:,1) was the results in x not the angle.

so the pendule have a stange behavior
after that I realised the angle was in radians not in degrees

so I changed cosd command to cos comand and sind comand to sin

After that I realised the time array was wrong it make the video with a low resolution:

So I changed the tspan from (0,100,100) to (0,100,500)
After that the pendule have the right behavior acconrding to the video attached: