Challenge

Solving second order ODEs

Challenge:

Solving ODE for pendulum swing for the given inputs

Code for plotting and animation:

%Code for solving Second Order ODE 
clear all
close all
clc

%Inputs
b = 0.05;               %Damping Co-efft
g = 9.81;               %Accleration due to gravity
l = 1;                  %Lenght of Pendulum 
m = 1;                  %Mass

%Initial Conditions
theta_0 = [0 ; 3];      %Initial Displacement and Velocity

%Time points
t_span = linspace(0,20,500);

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

%Plotting Displacement and Velocity
plot(t, results(:,1))
hold on
plot(t, results(:,2))
ylabel('Plot')
xlabel('Time')
legend('Displacement','Velocity')

%Inputs for Pendulum Swing Animation
x0 = 0;
y0 = 0;
ang_disp = results(:,1);
x1 = l * sin(ang_disp);
y1 = - l * cos(ang_disp);

%For loop to plot pendulum swing as per different angular displacements
ct = 1;                         %Variable for capturing Movie Clips
figure
for i = 1 : length(x1)
    x2 = x1(i);
    y2 = y1(i);
    %Plot- Fixed Line; Pendulum mass; String.
    plot([-0.1 0.1],[0 0],x2,y2,'o',[x0 x2],[y0 y2],'linewidth',3)   
    axis([-1 1 -1.5 0.5])
    pause(0.1)
    
    M(ct) = getframe(gcf);
    ct= ct+1;
end

%Animation creation
movie(M)
videofile = VideoWriter('Pendulum_Swing.avi','Uncompressed AVI');
open(videofile)
writeVideo(videofile, M)
close(videofile)

Code for Function:

%ODE Funtion for Displacement and Velocity
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

Results:

1. Dispacement and Velocity graph

2. Pendulum Swing Animation

Explanation:

Above is the code to solve ODE to get Displacement and Velocity values for Pendulum, using ODE45 function in Matlab. Code 1 is for Plotting the results and generating the animation for the pendulum swing. Code 2 is for the Function of Velocity and Angular Displacement.

The ODE is solved as per the following logic:

`(d^2θ)/(dt^2)+(b/m)(dθ)/dt+(g/L) sinθ = 0`

`θ = θ1 ; (dθ)/dt=(dθ1)/dt=θ2; (d^2θ)/(dt^2)=(d^2θ1)/(dt^2)=(dθ2)/dt`

`(dθ2)/dt = -(b/m)θ2-(g/L)sinθ1`

`(d/dt)[[θ1],[θ2]] = [[θ2, ],[(-b/m)θ2,(-g/l)sinθ1]]`

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.