Project

Simulating motion of a simple pendulum by solving differential equation

%PROGRAM TO SIMULATE MOTION OF SIMPLE PENDULUM

clear all
close all 
clc

%Inputs
l=1; %Length of the string in m
g=9.81; %Gravity in m/s^2
m=1; %Mass in kg
b=0.05;

%For simplification
r=g/l ;
k=b/m ;

%Initial conditions
theta_0=[0,3]; %[Angular displacement,Angular-velocity]

%Time
t_span=linspace(0,20,500);

%Pendulum ODE
f=@(t,x) [x(2);-k*x(2)-r*sin(x(1))];

%[t,Results]=ode45('challange_2nd_ode',t_span,theta_0);

[t,x]=ode45(f,t_span,theta_0);
subplot(5,4,[13,14,17,18]);
%Plot the solution
plot(t,x(:,1),'color','b');
hold on;
plot(t,x(:,2),'color','r');
hold off ;
subplot(5,4,[15,16,19,20]);
plot(x(:,1),x(:,2));
xlabel('position-Radians');
ylabel('Angular Velocity');

ct=1;
for i=1:length(x(:,1))
    x0=0;
    y0=0;
    x1 = 1*sin(x(i,1));
    y1 = -1*cos(x(i,1));
    subplot(5,4,[1,2,3,4,5,6,7,8,9,10,11,12]);
    plot([-1,1],[0.0],'linewidth',10,'color','k');
    hold on
    line([x0 x1],[y0 y1],'linewidth',5,'color','b');
    axis([-1.5 1.5 -1.5 0.5])
    hold on;
    plot(x1,y1,'-o','markers',20,'markerfacecolor','r');
    %grid on;
    plot([-1 1],[0 0],'linewidth',5,'color','g')
    grid on;
    
    %pause(0.001);
    text= sprintf("pendulum%d.png",ct);
    saveas(1,text)
    pause(0.001); 
    hold off
    %q(ct)*getFrame(gcf);
    %^Text*sprintf("pendulum%d.png",ct);
    %saveas(1,Text)
    ct=ct+1;  
 end
 









EXPLANATION

Here,simple pendulum motion is simulated by solving second orderdifferential equation with the help of ODE solver called ode45 which will provide us the values of angular displacement and angular velocity for differernt time instance.Here total time span of 20secs are divided into 500 parts.Here the results obtained after solving ode45 are stored in the array called [t,x].Now the each angular displacement values are accesed from the result obtained from ode45 by using for loop in order to calculate x1 and y1 coordinate of the pendulum.Coordinates obtained are joined with origin with the help of line command.Now the coordinate obtained at each and every time instances are stored in the form of imsge png format.There are 500 images generated which is combined with the help of imagemagic tool to get the desired simulation output.

PLOT

Youtube link for video:

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.