Programming pendulum Oscillation using Ordinary Differential Equations
function [dtheta_dt] = pendulum_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
clear all
close all
clc
b = 0.05;
g = 9.81;
l = 1;
m = 1;
%initial Conditions
theta_0 = [0;3];
%time points
t_span = linspace(0,20,500);
%solve ODE
[t, results] = ode45(@(t,theta) pendulum_func(t, theta,b,g,l,m),t_span, theta_0);
ct = 1;
for i = 1:length(results)
THETA = results(i,1);
x = 0;
y = 0;
x1 = 1*sin(THETA);
y1 = -1*cos(THETA);
hold on
%Plotting a reference line
plot([-1,1],[0,0],\'Linewidth\',4,\'color\',\'k\')
%Plotting the line that connects the ball and the fixed end
plot([x,x1],[y,y1],\'Linewidth\',3,\'color\',\'b\')
%PLotting the ball positions
plot(x1,y1,\'marker\',\'o\',\'markerfacecolor\',\'r\',\'markersize\',20)
axis([-1 1 -1.5 0.2])
pause(0.005)
M(ct)=getframe(gcf);
ct=ct+1;
% CLearing the image stored previously
clf()
end
%Animating the Pendulum Occilation
movie(M)
Videofile = VideoWriter(\'Pendulum Oscillation.avi\',\'Uncompressed AVI\')
open(Videofile)
writeVideo(Videofile,M)
close(Videofile)
To calculate the to position of the ball i created a function to represent the movement by using the ODE.
Then in the main programming I defined all the available values. Then by using the defined function i calculated the values of displacement and velocities.
Then to create images for the video to represent the movement of the ball, I used for loop and used the displacement values. I created a line representing a fixed base. Then created a line joining the ball and the fixed line. Then i defined the ball positions.
I then stored the images in a variable \'M\'. After that I created a video file.
I used clf() command to clear the current figure.
The error that I faced was that all the images overlapped each other. I then searched online for the solution and found clf() command.