Week 3 - Solving second order ODEs
% Objective: Solving second order ODEs of a penedulum
clear all
close all
clc
b = 0.05;0
g = 9.81;
l = 1;
m = 0.1
% initial condition
theta_0 = [0;5]
% time span
t_span = linspace(0,10,500)
% solving ODE
[t,results] = ode45(@(t,theta) ode_func(t, theta, b,g,l,m), t_span, theta_0);
%Plotting
figure(1)
hold on
plot(t,results(:,1))
plot(t,results(:,2))
title('Damped Harmonic motion of a Pendulum')
legend('Angular displacement', 'Angular velocity')
ylabel('Plot')
xlabel('Time(seconds)')
% For loop
ct =1;
for i = 1:length(results(:,1))
x_start = 0
y_start = 0
x_end = l*sin(results(i,1))
y_end = -l*cos(results(i,1))
%animation
figure(2)
plot([-1 1], [0 0], 'linewidth', 5)
hold on
plot([x_start x_end],[y_start y_end],'linewidth',3)
hold on
plot(x_end,y_end,'o','markersize',30 ,'markerFacecolor','b')
title('Animation of transient behaviour of a Pendulum')
axis([-1.5 1.5 -1.5 1])
pause(0.03)
hold off
M(ct) = getframe(gcf)
ct = ct+1
end
% Animation of the pendulum
movie(M)
videofile=VideoWriter('Pendulum Animation.avi', 'uncompressed avi')
open(videofile)
writeVideo(videofile,M)
close(videofile)
%ode_func code
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/1)*sin(theta1);
dtheta_dt=[dtheta1_dt;dtheta2_dt];
end
pendulum animation video drive link
https://drive.google.com/file/d/18P9ldyqWCgek0QQAxwoxvJgAqk9V3h9z/view?usp=sharing
explanation of the code
- starting the code with the clear codes (clear all, close all , clc).to erase any previous exicutions.
- state the given values such as damping coefficient,gravity, length of the string, and mass of the ball.
- state the initial condition of the angle (theta) of the string which is maximum in the initial state.
- time span is given as an array of matix ranging from 0-10 with 500 values.
- then the ode function is solved useing a function load file as ode_func
- ode_func is used to dictate the 2nd order ode equation.
- plotting is done for the values(t,results) named as figure 1
- title,legend, axis labels are given to the respective domains.
- for loop is created for the animation of the pendulum which is named as figure 2.
- for animation of the figure 2 plot command is used for the signification of the pendulum.
- the animation of the pendulum is writen as pendulum animation.avi.
errors occured during writing of the code
- error due to previous exicutions.
- spelling mistake during codeing.
- animation block mistrakes such as animation speed, model etc
steps taken to avoid the errors.
- written clear all code at first to avoid any previous exicutions interferance.
- spell check of the code.
- giving correct parameters to avoid errors in animation.