Challenge

SOLVING SECOND ORDER ODE'S

AIM :

To solve an ordinary differential equation (ODE) and use the calculated information to animate the motion of the simple pendulum using MATLAB.

FILES : ODE_CODES

THEORY :

An ODE is a differential equation containing one or more functions of one independent variable and derivatives of those finctions. The ODE equation and calculations are give below :

CODING :

Function to solve the ODE in the main program :

% Function to solve the ODE

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

Main Program :

clear all
close all
clc

%Input parameters
b = 0.05;  %Damping Coefficient
g = 9.81;  % Acc. due to Gravity (m/s^2)
l = 1;     %Length of the spring (m)
m = 0.1;   %Mass of the bob (Kg)

%Initial Displacement and Velocity in matrix
theta_0=[0;5]

% Time span of pendulum oscillation
t_span = linspace(0,25,500)

%Solving ODS

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

%Plotting
figure(1)
hold on
plot(t,result(:,1))
plot(t,result(:,2))
legend('Angular Disp','Angular Velocity')
xlabel('Time')
ylabel('Plot')

%Pendulum Animation
ct = 1;
for i = 1:length(result(:,1))
    
    %Initial position
    x0 = 0
    y0 = 0
    
    %Final position
    x1 = l*sin(result(i,1))
    y1 = -l*cos(result(i,1))
    
    figure(2)
    
    %Base of Pendulum string
    plot([-1 1],[0 0],'linewidth',3);
    hold on
    plot([x0 x1],[y0 y1],'linewidth',2);
    hold on
    plot(x1,y1,'-o','markersize',20,'markerFacecolor','y') %Pendulum
    axis([-2 2 -2 2]) %To get the correct oscillation within the graph
    hold off
    
    A(ct) = getframe(gcf)
    ct=ct+1;
    
end


%Animation like before
movie(A)
videofile = VideoWriter('Animation.avi','uncompressed avi')
open(videofile)
writeVideo(videofile,A)
close(videofile)
    

Here Ode45 was used which is an inbult in function in Matlab that solves ordinary differential equations using a numerical method. Here in this program it takes in 3 inputs :

  • Integrating function
  • Time span
  • Initial Conditions

RESULT :

Harmonic motion of a Pendulum :

Pendulum motion :

ERRORS OCCURRED :

  • This occurred due to a type error in the variable name which was fixed.

  • The code writevideo should be writeVideo with 'V' as upper case.



  • A negative sign was not inserted in the formula which resulted in the upside down pendulum.

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.