Pendulum with damping animation using MATLAB
clear all
close all
clc
%Inputs that the ODE Function requires.
b=0.05;
m=1;
l=1;
g=9.81;
ct=1;
%Initial conditions for displacement and velocity.
theta0=[0;2.5];
% Time span
t_span=linspace(0,20,500);
% Function Call: Two outputs are generated, time and results, of which
% results has displacement and velocity solutions.
[t, results]=ode45(@(t,theta)ODE_Func(t,theta,b,g,l,m),t_span,theta0);
%Initialising the for loop, from 1s to length of t/results.
for i=1:length(results)
THETA=results(i,1);
% Values for end position of mass is calculated using geometry.
x1=(l*sin(THETA));
y1=l*(-cos(THETA));
%First point to which rope is connected.
x0=0;
y0=0;
% Plotting of the rope
plot([x0 x1],[y0 y1],\'color\',\'r\',\'linewidth\',3)
hold on
% Plotting of the end position of the mass that behaves according to
% the solution of the ODE.
plot(x1,y1,\'O\',\'Markersize\',20,\'color\',\'k\')
axis([-1.5 1.5 -1.5 0]);
title(\'Simple Pendulum Animation\') % After setting axis, only one shot.
pause(0.1)
hold off
% Frames stuffed into an array N.
N(ct) = getframe(gcf);
ct=ct+1;
end
% Procedure to save the animation as AVI
videofile=VideoWriter(\'Pendulum.avi\',\'Uncompressed AVI\');
open(videofile);
writeVideo(videofile,N);
close(videofile);
%3 Problems: Axis Setting, Y value not changing, not ale to plot both line
%and point since hold on cannot be used.
Function::
function [dtheta_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);
dtheta_dt=[dtheta1_dt ; dtheta2_dt];
end
Errors:
Sind and cosd were used instead of sin and cos. error was clarified with support engineer.
All plots were coming on the same figure window as hold off was not used immedietely after the pause command. Also, hold on was used before the first plot command, the first plot had to be held till the second one executes. It was clarified with the support engineer.
Code Explanation:
1) The function to solve the ODE is first set up, The input arguments are b,g,l,theta,t_span etc.
2) The system of 1st order ODEs were inputted and the solution matrix was created.
3) In the main program, the inputs were given and the function was called.
4) the outputs from the function were stored in 2 variables, time and results, results also was an array consisting of length(t_span) rows.
5) In the for loop, the value of x1 and x2 were calculated geometrically using theta from the solution.
6) Then for plotting, the initial point is (0,0) and the plot of the rope was given.
7) Then x1, x2 mass point was given to be plotted after hold on was put in.
8) Then the procedure to create multiple frames and store than in an array was used, using pause function.
9) It was then written into an AVI file.