Challenge

Week 4.1 - Solving second order ODEs

ODE-FUNC CODE

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

MATLAB-CODE

close all %Closes all the open windows
clear all %Clears the workspace
clc       %Clears command window

%This program is for solving the second order differential equation for a
%simple pendulum with damping

%The input or the parameters governing the pendulum motion

%Gravity is the gravitation force in m/s^2
g = 9.81;
%Length of the pendulum in m
L = 1;
%Mass of the pendulum in kg
m = 1;
%Damping co-efficient
b = 0.05;
%As the damping is less than we can say the system is underdamped

%time span for o to 20 seconds
t_span = linspace(0,20,501);

%Initial Condition
theta_0 = [0;3];
%The first value in colum matrix represents the angular displacement
%And the second value in column matrix represnts the initial velocity

%Solving the ODE
[t , results] = ode45( @(t, theta) ode_func(t, theta, b, g, L, m), t_span, theta_0);
%Over here we are calling the defining function along with input parameters
%t_span is the integral limit of our equation
%theta_0 shows the intial condition of the pendulum
%ode45 is the inbuilt solver used and values after the @ is shwoing that is
%the function of theta over the time

%This represents the displacement
plot(t,results(:,1))
hold on
%This represents the velocity
plot(t,results(:,2))
ylabel('plot')
xlabel('time')
hold off

position_x = results(:,1);
position_y = sqrt(L^2 - position_x.^2);

ct = 1;

for i = 1:length(position_x)
    
    plot([0 position_x(i)],[0 -position_y(i)],'Linewidth',3);
    hold;
    plot(position_x(i),-position_y(i),'o','color','magenta','Linewidth',5);
    axis([-1.5 1.5 -1.4 0.2]);
    pause(0.01);
    M(ct)=getframe(gcf);
    ct = ct + 1;
    
end

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

---------------------------------------------------------------------------------------------------------------------------------

OUTPUT LINK

The link to output is the youtube link - you can check the same by clicking on the below link

https://youtu.be/VIzSqMXMRmk
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.