Week 3 - Solving second order ODEs
function [dttheta_dt] = ode_proj(t,theta,b,l,m,g)
theta1 = theta(1)
theta2 = theta(2)
dtheta1_dt = theta2;
dtheta2_dt = -(b/m)*theta2-(g/l)*sin(theta1)
dttheta_dt = [dtheta1_dt;dtheta2_dt]
end
clear all
close all
clc
b = 0.03;
g = 9.81;
l = 1;
m = 1;
%initial condition
theta_0 = [0;3];
%time points
t_span = linspace(0,20,500);
%solve ode
[t,results] = ode45(@(t,theta)ode_proj(t,theta,b,l,m,g),t_span,theta_0);
plot(t,results(:,1))
hold on
plot(t,results(:,2))
xlabel('time')
ylabel('displacement/velocity')
legend('displacement','velocity')
ct = 1
for i = 1:length(t)
x0 = 0
y0 = 0
x1 = l*sin(results(i,1))
y1 = -l*cos(results(i,1))
figure(2)
plot([-3 3],[0 0],'linewidth',2,'color','r')
line([x0 x1],[y0 y1],'linewidth',2)
axis([-1.5 1.5 -1.5 0])
hold on
plot(x1,y1,'o','markers',10,'markerfacecolor','cyan')
hold off
grid on
pause(0.03)
M(ct) = getframe(gcf)
ct = ct+1
end
movie(M)
videofile = VideoWriter('ODE_Project.avi','uncompressed avi')
open(videofile)
writeVideo(videofile,M)
close(videofile)
Creation of a function:
- Start the function, assign the function name and get the values from the input.
- Assume theta1 = theta(1) and theta2 = theta(2)
- Then we get to know dtheta1_dt = theta2 and dtheta2_dt = -(b/m)*theta2-(g/l)*sin(theta1) by solving.
- Finally we get the results as dttheta_dt = [dtheta1_dt;dtheta2_dt]
- End the function and save it as ode_proj.m
ode_program:
- Use the clear all, close all, clc to clear all the previous work done in Matlab.
- Get all the inputs that are needed.
- Get the initial condition of theta.
- Use linspace to get t_span from 0 to 20 with 500 divisions in between.
- Get [t,results] using ode45 and calling the created function ‘ode_proj.m’
- Plot and label the output.
- Then use ct =1 so that we can call the next value after the completion of one.
- Use for loop, where i = 1 to the length of t.
- Assing the initial and final values of x0, x1, y0, and y1.
- Then use plotline and axis command to show outputs.
- Markers are used to create the sphere of the pendulum.
- Pause is used to command the time between each frame.
- M(ct) is used to make a movie by getting the frame and the for loop is ended.
- A video file is created and the name is assigned.
https://drive.google.com/file/d/1z-mY7-_4s6DEcwICli28KfnCzP5edKtd/view?usp=sharing