Speed Programming in Matlab/Octave for non computer science engineers(Simple pendulum)
Simple pendulum:
A simple pendulum consists of a mass m hanging from a string of length l and fixed at a pivot point P. When displaced to an initial angle and released, the pendulum will swing back and forth with the periodic motion. And it depends upon Newton's second law of motion.
Given equation
d2θ/dt2 + (b/m)(d2θ/dt) + g sinθ/l = 0 (1)
g = gravity in m/s2 = 9.81 m/s2,
L = length of the pendulum in m = 1m,
m = mass of the ball in kg = 1kg,
b=damping coefficient = 0.050.
θ = θ1
dθ/dt = dθ1/dt = θ2 (2)
d2θ1/dt2 = dθ2/dt (3)
substitute equations 2,3 in eq 1.
dθ2/dt + (b/m)* θ2 + g sinθ/l = 0
dθ2/dt = -(b/m)* θ2 - g sinθ/l (4)
from equations 2 & 4
d/dt [ θ1 ] = [ θ2 ]
d/dt [ θ2 ] = [-(b/m)* θ2 - g sinθ/l ]
by solving θ1, θ2, we can get the second order ODE of simple pendulum.
code for odefun simple pendulum:
function [ydot] = odefun_s_pendulum(t,y);
g = 9.81;
l = 1;
b= 0.05;
m=1;
ydot = zeros(2,1);
% rate of change of displacement = velocity;
ydot(1) = y(2);
�celeration = -(b/m)*y(2)-(g/l)*sin(y(1));
ydot(2) = -(b/m)*y(2)-(g/l)*sin(y(1));
endfunction
code for a simple pendulum:
% solving a simple pendulum
close all
clear all
clc
t = linspace(0,20,400);
y0 = [0 3];
[t,y] = ode45('odefun_s_pendulum',t,y0);
figure 1
plot(t,y(:,1),'color','b','linewidth',2)
hold on
plot(t,y(:,2),'color','r','linewidth',2)
xlabel('time')
ylabel('displacement,velocity')
legend('displacement','velocity')
figure 2
plot(y(:,1),y(:,2),'linewidth',2)
xlabel('position')
ylabel('velocity')
ct = 1;
for i = 1:length(y(:,1));
x0 = 0;
y0 = 0;
x1=1*sin(y(i,1));
y1=-1*cos(y(i,1));
figure(3)
plot([-0.1 0.1],[0 0],'linewidth',2);
hold on
plot([x0 x1],[y0 y1],'color','r','linewidth',2);
hold on
plot(x1,y1,'marker','o','markersize',40,'markerfacecolor','b');
hold off
axis([-1 1 -1.5 0]);
printf("Creating GIF- Progress... %d/%d\n", i, length(t));
img = print("-RGBImage");
imwrite(img, "animation.gif", "DelayTime", .005,"compression","bzip","WriteMode","Append");
end
##movie(M)
##videofile = videowriter('pendulum.avi','uncompressed avi');
##open(videofile)
##writevideo(videofile,M)
##close(videofile)
plot for time and displacement and velocity:
plot for position and velocity:
Animation link in youtube:
httpswww.youtube.comwatchv=T_cghmJMx7Y