Challenge

Week 3 - Solving second order ODEs

close all
clear all
clc

% Defining the input data for the simple pendulum
b = 0.01;    %Damping co-efficient 
g = 9.81;    %Acceleration due to gravity (Unit - m/s2)
l = 1;       %Length of the pendulum (Unit - m)
m=0.1;       %Mass of the pendulum (Unit - kg)

% Defining the initial condition in order to solve the 2nd ODE which is
% represented as two first ODE's in the form of angular 
% velocity & displacement
% Initial angular displacement assumed is 0 rad 
% Initial angular velocity assumed is 5 rad/s

theta_0 = [0;5]; 

% In order to solve our ODE that needs to be integrated in order to obtain 
% a solution, a time constraint needs to be defined

t_span = linspace (0,10,750);

% Solving our ODE
% 2 functions are used "ode45" and "ode_func"
% "ode45" fuction is an in-built matlab function and it's input parameters
% being called will be (t,theta)
% "ode_func" is the defined function whose input values called are
% (t,theta,b,g,l,m) and finally 2 conditions (theta_0 & t_span) are called

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

% Plotting the ODE solver equations

figure(1)
plot(t,results)
xlabel('TIME')
ylabel('PLOT')
legend('Angular Displacement(rad)', 'Angular Velocity(rad/s)')

% Creating the animation for the pendulum

ct=1;   % Initializing the frame counter variable to 1

for i=1:length(t)
    x=l*sin(results(i,1));
    y=-l*cos(results(i,1));
    
    figure(2) 
    
    plot ([-2 2], [0 0], 'linewidth', 5, 'color', 'red')
    grid on
    hold on
    plot([0 x], [0 y], 'linewidth', 3, 'color', 'b')
    plot(x,y, '-O', 'Markersize', 15, 'MarkerFacecolor', [rand rand rand], 'MarkerEdgeColor', 'cyan')
    
    hold off
    axis([-2 2 -2 2])
    
    M(ct)=getframe(gcf);   % 'M' vector collects the frames 
    ct=ct+1;
    
end

ODE_video = VideoWriter('ode_1')  % 'ode_1' is file name saved
open(ODE_video)
writeVideo(ODE_video, M)   % Writing the 'M' vector data onto 'ode_1'     
close(ODE_video)



% YOUTUBE ANIMATION >>>> https://youtu.be/m43iPjtfB_8










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.