Challenge

Week 3 - Solving second order ODEs

Aim: To simulate a pendulum motion by solving the following 2nd ODE equation as shown below:

In the above equation,

g = 9.81 m/s², L (length of the pendulum)= 1m, m = mass of the ball=1 kg, b=damping coefficient= 0.5. Simulation period = 20sec

angular displacement=0,angular velocity=3 rad/sec at time t=0.

Method:

  • For each value in time the position of the pendulum is calculated
  • An image that represents the position of the pendulum is plotted after solving the ODE (using function call) with a fixed pivot point
  • Each calculated and plotted position is captured in frames to stitch to a movie (Matlab function)
%Matlab code to animate a pendulum in motion with mass, length of arm,
%velocity and acceleration , and drag/damp co-efficient known

clc
clear all
close all

%damp_coeff = b
b=0.05;
%acceleration of pendulum mass(m/s^2)=g
g=9.8;
%Length of pendulum=l
l=1;
%mass=m
m=1;

%pendulum position and velocity
theta0=[0;3];

%Time as position marker (t1)
tspan=linspace(0,20,200);

%simple ODE
[t,results]= ode45(@(t,theta) ode_func(t,theta,b,g,l,m),tspan,theta0);

Angle = results(:,1);

    ct=1;
for i=1:length(Angle)
    angle=Angle(i);
figure(ct)
%Pivot point
x0=1;
y0=2;

%ball coordinates
x1=l*sin(angle)+x0;
y1=-l*cos(angle)+y0;

%Animating pendulum
%coordinates of pendulum rod and ball-mass
axis([0,2,0,2.75])
hold on
plot([x0,x1],[y0,y1],'linewidth',3,'color','[0.9290 0.6940 0.1250]');
hold on
plot(x1,y1,'.','color','r','linewidth',15,'markersize',40);
plot(x0,y0,'o', 'color','k','linewidth',15,'markersize',2);
M(ct)= getframe(gcf);
ct=ct+1;
hold off
end

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

Function to solve the 2nd order function:

function [Theta_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);
Theta_dt=[dtheta1_dt ; dtheta2_dt];
end

Click here to view the video

Conclusion:

  1. Breaking down complex equations 2nd order and above to simple form and solving is an easy way to get solutions
  2. Learned to use ODE45 function predefined by MATLAB
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.