Solving ode for pendulum
Function for pendulum is as follows
function [zdot] = odefun_second_order_pendulum(t,z)
% let z = angle
%given data
L=1;
m=1;
b=0.5;
g=9.81;
z1=z(1);
z2=z(2);
zdot(1)=z(2);
zdot(2) =(-b/m)*z2-(g/L)*sin(z1);
zdot = [zdot(1),zdot(2)]\';
end
Below is the program for solving second order ODE.
clear all
close all
clc
% Solving a second order ODE for pendulum
%z = angle
%Given data
L=1;
m=1;
b=0.5;
g=9.81;
ts = linspace(0,20,100); %timespan
z0 = [0 3]; % initital conditions
[t,x]= ode45(\'odefun_second_order_pendulum\',ts,z0);
%plotting
figure(1)
plot(ts,x(:,1),\'r\');
hold on
plot(ts,x(:,2),\'b\');
hold on
legend(\'Angular Displacement\',\'Angular Velocity\');
xlabel(\'time\');
saveas(gca,\'Pendulum plot.jpg\');
%animation
x0 = 0;
y0 = 0;
x1 = L*sind(x(:,1));
y1 = -L*cosd(x(:,1));
for i=1:size(x(:,1))
x_1= x1(i);
y_1= y1(i);
figure(2)
plot([x0,x_1],[y0,y_1],\'linewidth\',4,\'color\',\'bla\',\'marker\',\'s\',\'markerfacecolor\',\'g\',\'markersize\',10);
hold on
rectangle(\'Position\',[-0.05,0,4,0.5],\'Facecolor\',\'blue\');
line([0 0],[-1.5 1],\'LineStyle\',\'--\',\'linewidth\',2,\'color\',\'bla\')
hold on
plot(x_1,y_1,\'-o\',\'markerfacecolor\',\'y\',\'markersize\',50);
plot(x_1,y_1,\'-o\',\'markerfacecolor\',\'bla\',\'markersize\',5);
hold on
axis([-0.02 0.02 -1.5 0.5]);
Y(i)=getframe(gcf);
i=i+1;
hold off
drawnow
end
movie(Y)
videofile = VideoWriter(\'Simple_Pendulum_Animation.mp4\',\'MPEG-4\');
open(videofile)
writeVideo(videofile,Y)
close(videofile)
Result of Time vs Displacement and velocity plot.
Youtube animation link
https://youtu.be/hVBky00BsG4