Challenge

Week 3 - Solving second order ODEs

Motion of a Pendulum – Solving 2nd Order ODEs

Main body of the program:

% Motion of a pendulum
close all
clear all
clc

% Inputs
L = 1; %[length in m]
m = 1; %[mass in kg]
b = 0.05; %[damping coefficient]
g = 9.81; %[in m/s^2]

% Initial condition
theta = [0;3]; % a vector that stores the initial values
% at t=0s angular displacement = 0 and angular velocity = 3rad/s

% Simulation time
t_initial = linspace(0,20,500);

% Solving the ODE
[t,results] = ode45(@(t,theta) ode_func(t,theta,L,m,b,g),t_initial,theta);

% Plots
figure(1)
plot(t,results(:,1),'color','r') % Angular displacement vs time 
hold on
plot(t,results(:,2),'color','b') % Angular velocity vs time
xlabel('Time')
ylabel('Angular Displacement and Angular Velocity')
hold off

theta_m = results(:,1); % Storing the calculated angular displacement in a new vector
ct = 1; % Counter variable


for i = 1:length(theta_m)
    THETA = 2*theta_m(i); % To visualise the motion better, the angular displacements are multiplied with a factor
    x0 = 0;
    y0 = 0;
    
    % Calculating the x and y coordinates based on the angular displacment
    x1 = L*sind(THETA); 
    y1 = L*cosd(THETA);
    
    % Plotting the motion based on the calculated coordinates
    figure(2)
    plot([x0 x1],[y0 -y1],'-o','MarkerSize',15,'MarkerFaceColor','r','LineWidth',3)
    % here -y1 is used to visualise the motion in the right manner
    axis([-1 1 -1.5 0.5])
    M(ct) = getframe(gcf); % Capturing each figure to create an animation
    ct = ct+1;
end

% Creating the animation
movie(M)
new_vid = VideoWriter('motion_of_a_pendulum','Uncompressed AVI');

open(new_vid)
writeVideo(new_vid,M)
close(new_vid)

Function body:

% Objective function
% Defintion of the ODE

function [dtheta_dt] = ode_func(t,theta,L,m,b,g)
theta1 = theta(1); % Angular displacement
theta2 = theta(2); % Angular velocity
dtheta1_dt = theta2;
dtheta2_dt = (-b/m)*theta2 - (g/L)*sind(theta1); % Equation of motion of the pendulum
dtheta_dt = [dtheta1_dt; dtheta2_dt];
end

Report: https://drive.google.com/file/d/1fPsCxMQvktqaLewwt-s8-V8XQpJ3MURe/view?usp=sharing

Animation file link: https://drive.google.com/file/d/1lB9lITJNceFhbzVQ2Y64ATAqvNPiHVv2/view?usp=sharin

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.