Challenge

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:

  1. Start the function, assign the function name and get the values from the input.
  2. Assume theta1 = theta(1) and theta2 = theta(2)
  3. Then we get to know dtheta1_dt = theta2 and dtheta2_dt = -(b/m)*theta2-(g/l)*sin(theta1) by solving.
  4. Finally we get the results as dttheta_dt = [dtheta1_dt;dtheta2_dt]
  5. End the function and save it as ode_proj.m

ode_program:

  1. Use the clear all, close all, clc to clear all the previous work done in Matlab.
  2. Get all the inputs that are needed.
  3. Get the initial condition of theta.
  4. Use linspace to get t_span from 0 to 20 with 500 divisions in between.
  5. Get [t,results] using ode45 and calling the created function ‘ode_proj.m’
  6. Plot and label the output.
  7. Then use ct =1 so that we can call the next value after the completion of one.
  8. Use for loop, where i = 1 to the length of t.
  9. Assing the initial and final values of x0, x1, y0, and y1.
  10. Then use plotline and axis command to show outputs.
  11. Markers are used to create the sphere of the pendulum.
  12. Pause is used to command the time between each frame.
  13. M(ct) is used to make a movie by getting the frame and the for loop is ended.
  14. A video file is created and the name is assigned.

https://drive.google.com/file/d/1z-mY7-_4s6DEcwICli28KfnCzP5edKtd/view?usp=sharing

Your portfolio, next

Ship work like this
in your own course.

Talk to a career counsellor

Free 20-minute call. We'll map the right course to where you want to work.

By submitting you agree to our Terms and Privacy Policy.

Talk to a career counsellor

Free 20-minute call. We'll map the right course to where you want to work.

By submitting you agree to our Terms and Privacy Policy.