Challenge

Week 3 - Solving second order ODEs

STEP 1: CLEARING THE PREVIOUS OUTPUT SCREEN AND INITIALIZING THE VALUES

clear all
close all
clc

b = 0.05;%damping coefficient
g = 9.81;%gravity
l = 1;%length
m = 1;%mass

STEP 2: DEFINING THE INITIAL CONDITION AND THE TIME INTERVAL

%initial condition
theta_0 = [0;5];

%time points
t_span = linspace(0,10,500);

STEP 3: ODE FUNCTION DECLARATION

%solve ODE
[t,results] = ode45(@(t,theta) ode_func(t,theta,b,g,l,m),t_span, theta_0);

STEP 4: FUNCTION DEFINITION

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

STEP 5: PLOTTING

%Plotting
figure(1)
plot(t,results(:,1))
hold on
plot(t,results(:,2))
ylabel('Plot')
xlabel('Time')
grid on

STEP 6: CREATING THE ANIMATION OF SIMPLE PENDULUM USING FOR LOOP

%Animation
figure(2)
ct = 1;
for i = 1: length(t_span)
    x0 = 0;
    y0 = 0;
    x1 = 1*sind(results(i,1));
    y1 = -1*cosd(results(i,1));
    plot([x0 x1],[y0,y1],[-0.5 0.5],[0 0],'linewidth',3)
    hold on
    plot(x1,y1,'marker','o','markersize',30,'markerFacecolor','r')
    axis([-1.5 1.5 -1.5 0.5])
    grid on 
    pause(0.0001)
    M(ct) = getframe(gcf);
    ct = ct+1;
    hold off
end

STEP 7: CREATING A MOVIE OF THE ANIMATION AND WRITING IT INTO A FILE

movie(M)
videofile = VideoWriter('ode_function.avi','Uncompressed AVI');
open(videofile)
writeVideo(videofile,M)
close(videofile)

YOUTUBE LINK OF THE ANIMATION: https://youtu.be/6FS2XtQ3l84

NO ERRORS FACED

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.