Challenge

Week 3 - Solving second order ODEs

Objective: To create a Matlab code to solve the second deferential equation and make an animation of pendulum motion.

Theory: The motion of a single pendulum can be described as the below equation:

In which theta is the angle in degree, m is mass in kg, b is constant cofficient, g is grviational accelearion in m/s2, and L is the length of the pendulum in m as shown below:

Matlab codes:

%%
clear all
close all
clc
% Inputs:
c=0.05;% damping coefficientdue
g=9.81;% gravitational acceleration
l=1; %length of the pendulum
m =0.1;% body mass

%input required for the pendulum as intitial condition
theta_0 =[0;3];
%time span of pendulum
time_span = linspace(0,20,400);
% solving ODE equation 
[t , results] = ode45(@(t,theta) ode_fun(t,theta,c,g,l,m),time_span,theta_0);
plot(t,results(:,1),'color','g')
hold on
plot(t,results(:,2),'color','r')

%using for LOOP to get different values of theta
ct = 1 ;
for i= 1:length(results(:,1))
  x0=0;
  y0=0;
  x1=l*sin(results(i,1));
  y1 = -1*cos(results(i,1));
  subplot(5,4,[1,2,3,4,5,6,7,8,9,10,11,12]);
  plot([1 1],[0 0],'LineWidth',3,'color','c');
  hold on
  line([x0 x1] , [y0 y1],'linewidth',2,'color','m');
  hold on
  %set a sphere to represent the moemant
  plot(x1,y1,'-o','markers',30,'markerfacecolor','b');
  
  grid on;
  axis([-1.5 1.5 -1.5 0.5])
  pause(0.0002);
  hold off
  q(ct) = getframe(gcf);

  ct = ct+1;
end
% creating a movie.
movie(q)
videofile=VideoWriter('Damped_Pendulum.avi','uncompressed avi');
open(videofile)
writeVideo(videofile,q)
close(videofile)

Codes for ODE45 Function:

function [dtheta_dt] = ode_fun(t,theta,c,g,l,m)
    theta1 = theta(1);
    theta2 = theta(2)
    dtheta1_dt = theta2;
    dtheta2_dt = -(c/m)*theta2-(g/l)*sin(theta1);
    dtheta_dt = [dtheta1_dt ; dtheta2_dt];
end

Program codes:

Providing the inputs and the intinal condition of movement in this case assumed there will be a damping in the movemnet of the pendulum. Then writing a function to solve for the second differential equation using ODE45, and using for loop for different values of theat, plotong the result and make a video as an output.

Output:

A video simulate the movement of simple pendulum with giving damping constant and time range range 20 s.

Youtube:https://youtu.be/jjzLr6i3XTw

Conclusion:

The matlab codes can simulated the movement of the pendulum using different damping cofficient. in case the damping is zero there will no drag force of the peudulum so in is case it will oscilate for ever.

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.