Project

Solving 2nd order ode for simple pendulum and simulating it in MATLAB

  • I am going to solve a second order ODE for the simple pendulum and created a simulation of that pendulum in MATLAB.
  • How does the function program to solve the pendulum ODE look like?

Code for calling the function:

%Calling a function - pendulum ode solver

function [dtheta_dt] = pendulum_ode_solver(t, theta)

g = 9.81;
l = 1.5;
m = 0.5;

w = g/(l*m);
theta1 = theta(1);
theta2 = theta(2);
dtheta1_dt = theta2;
dtheta2_dt = -w*w*sin(theta1);
dtheta_dt = [dtheta1_dt;dtheta2_dt];
end
  • How does the code for solving the pendulum ODE and simulation look like?

Using the function program for pendulum ODE, the code for solving that ODE and simulation:

clear all
close all
clc

%Solving 2nd order ODE and creating animation for simple pendulum


%Initial conditions

theta0 = [0;6.5];
t_span = linspace(0,2,300);

%Solving the ODE
[t, results] = ode45(@(t,theta) pendulum_ode_solver(t, theta), t_span, theta0);

angular_disp = results(:,1);

%Animation

ct = 1;
for i = 1:length(t_span);
    THETA = angular_disp(i);
    
    %Coordinates for pendulum
    x0 = 0;
    y0 = 0;
    x1 = 1.5*sin(THETA);
    y1 = -1.5*cos(THETA);
     
    %Plotting for animation
    plot([-0.5 0.5],[0 0],[-0.5 -0.5],[0 0.08],[-0.5 0.5],[0.08 0.08],[0.5 0.5],[0.08 0],     'color','r','linewidth',3);
    hold on
    plot([x0 x1],[y0 y1], 'color', 'k', 'linewidth', 5)
    plot(0,0,'.','color','y')
    plot(x1,y1,'-o','markers',23,'markerfacecolor','b','color','b')
    hold off
    title('Simulating the motion of pendulum')
    axis([-2 2 -3 0.5])

     P(ct) = getframe(gcf);
    ct = ct + 1;

end

%Movie
movie(P);
videofile = VideoWriter('iSIMPLE_PENDULUM.avi','Uncompressed AVI');
open(videofile);
writeVideo(videofile, P);
close(videofile);

Animation:

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.