Aim of the project:
The aim of this challenge is to solve a second-order ordinary differential equation and simulate the motion of a pendulum.
% Program to solve the ode and simulate the motion of a pendulum.
% Declaring constants and initialising the values.
b=0.005;
g=9.81;
l=1;
m=1;
% Defining the parameters
theta_0 = [0;5];
t_span = linspace(0,10,500);
% Function calling statement.
[t,results] = ode45(@(t,theta) ode_func(t,theta,b,g,l,m),t_span,theta_0);
% Plotting the curve
figure(1)
plot(t,results(:,1))
hold on
plot(t,results(:,2))
xlabel('Time')
ylabel('Theta and Velocity')
%Simulation of the pendulum
ct =1;
for i = 1:length(results(:,1))
x0=0;
y0=0;
x1 = l* sin(results(i,1));
y1 = -l* cos(results(i,1));
figure(2)
plot([-1 1],[0 0],'linewidth',4,'color','k')
axis([-2 2 -2 2]);
hold on
line([x0 x1],[y0 y1],'linewidth',2,'color','b')
hold on
plot(x1,y1,'.','markersize',30,'color','r')
grid on
hold off
M(ct) = getframe(gcf);
ct = ct+1;
end
% Creating animation
movie(M)
videofile = VideoWriter('Pendulum_Movement.avi','Uncompressed AVI');
open(videofile)
writeVideo(videofile,M)
close(videofile)
%ODE 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