Challenge

Week 4.1 - Solving second order ODEs

Aim:

To write a program that solves the 2nd order ODE and also to animate the pendulum using matlab code.

Objectives:

The code solves the second order ODE and effectively simulates the motion of the pendulum systems. It also plots the ground, arm, pendulum ball. In addition to that, it creates a animation and saves it as a video.

clear all
close all
clc

%simulation of a second order ODE of a simple pendulum
%inputs
l = 1; % length of a pendulum in m
m = 1; % mass of the ball in kg
b = 0.05; % damping coefficient
g = 9.81; % gravity in m/s^2

%initial conditions
theta_0 = [0; 3]; %angular displacement and the angular velocity
t_span = linspace(0, 20, 500); %linearly spaced vector from 0 to 20 with 500 points

%calling ode_func and defining the ode45
[t, results] = ode45(@(t, theta) ode_func(theta, t, b, g, l, m), t_span, theta_0); 

plot(t, results(:, 1))
hold on
plot(t, results(:, 2))
xlabel('time')
ylabel('plot')

% Animate the pendulum
ct = 1; %loop counter
theta1=results(:,1);
for i = 1:length(t)
  THETA1=theta1(i);
  
    x0=0;
    y0=0;

    x1 = l*sin(THETA1);
    y1 = -l*cos(THETA1);
figure(2)
    plot([x0 x1], [y0 y1], 'r', 'LineWidth', 2);%this plot is from the origin to the pendulum's arm
    hold on
    plot(x1, y1,'.','MarkerSize',50);%this plot is for the ball
    hold on
    plot([-5 5],[0 0],'LineWidth',5);%this plot is for the horizontal line connecting the origin of the arm
    hold off
    axis([-9 9 -5 5])
    
    pause(0.01);
     M(ct) = getframe(gcf);% for getting current frame
    ct = ct + 1;
end
movie(M)
videofile = VideoWriter('simple_pendulum.avi', 'Uncompressed AVI');
open(videofile)
writeVideo(videofile, M)
close(videofile)


The function code is given below,

function [dtheta_dt] = ode_func(theta, t, 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

Graphs:

This graph tells that displacement starts at 0 and the velocity starts at 3. The time span is for 20 seconds.

The animation video for the simulation of simple pendulum has uploaded on the you tube and the link is given below,

https://youtu.be/skBXf-Na6Vg

Conclusion:

The code successfully achieves the objectives by solving second order differential equation using 'ode45' function for the time span of 20 seconds. The pendulum has been modeled using trignometric functions, so that the ball and the arm moves accordingly for each time step. Thus, the code effectively simulates and animates the motion for simple pendulum and allowing for better understanding of its behaviour and dynamics.

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.