Week 3 - Solving second order ODEs
https://drive.google.com/file/d/1a05FPlpUgImqmy6KCX4KolQE3LeEFtv-/view?usp=sharing
%given inputs
%damping coefficient
b=0.05;
%mass(kg)
m=1;
%length (m)
l=1;
%gravity(m/s^2)
g=9.81;
%initial condition
%angular displacement=0 and angular velocity =3 m/s
theta_0=[0;3];
%time span
%pendulum oscillates 0-20 secs
%linspace - 1st value represents starting point of angle
%2nd point refers ending point of angle and last point refers no of values
t_span=linspace(0,20,300);
%solving ODE
%here ode45 was used its a function that solves ordinary,partial differential equations
%here it is 4th order runge kutta method...
%calling the function ode_func
[t,results]=ode45(@(t,theta) ode_func(t,theta,b,m,g,l),t_span,theta_0);
%plotting angular displacement and angular velocity with respect to time
figure(1)
plot(t,results(:,1))
%hold on used to add new plot in existing plot
hold on
plot(t,results(:,2))
%title is used for title of plot
title('motion')
%legend is used to create labels for each plot
legend('angular dispalacement','angular velocity')
%xlabel is used to define x axis
xlabel('time')
%ylabel is used to define y axis (i:e) displacement and velocity
ylabel('plot')
%counter was defined before starting for loop
%at every position of the ball ct stores the data
ct=1;
%for loop allows code to executed repeatedly the start and end points have
%been defined
for i=1:length(results(:,1))
%x0 and y0 is fixed point
x0=0;
y0=0;
% x1 and y1 will be position of ball
x1=1*sin(results(i,1));
y1=-1*cos(results(i,1));
%plotting pendulum for motion
figure(2)
%plot for fixed line
plot([-1 1],[0 0])
hold on
%pendulum string as line in blue color
plot([x0 x1],[y0 y1],'linewidth',5,'Color','b')
hold on
%bob fixed to string with size 40 and red color
plot(x1, y1,'o','markersize',40,'Color','r')
%axis limits respect to x,y axis
axis([-1.5 1.5 -1.5 1])
%pause command gives better visualization of the plot
pause(0.03)
hold off
%ALL total frames resulting are stored in array M
%getframe captures the individual frame in gcf
M(ct)=getframe(gcf)
%ctrepresents every frame the counter(ct) is incremented by 1(ct+1)
ct=ct+1
end
%making the video file
%movie is used to create video of frames generated to variable M
movie(M)
%videowriter is used to assign the format of the video
%here avi format is used
videofile=VideoWriter('simple_pendulum.avi','uncompressed AVI');
%open command is used to open the video
open(videofile)
%write video is used to write the video with plot frames
writeVideo(videofile,M)
%close command is used to close the video file
close(videofile)
%function program will be called in main program to solve ode
%here 0=01 and d01/dt=02 in given equation
function [dtheta_dt] = ode_func(t,theta,b,m,g,l)
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