Simulating a pendulum using second order ode
In Engineering, ODE is used to describe the transient behavior of a system. A simple example is a pendulum The way the pendulum moves depends on the Newtons second law. When this law is written down, we get a second order Ordinary Differential Equation that describes the position of the "ball" w.r.t time. Similarly, there are hundreds of ODEs that describe key phenomena and if we have the ability to solve these equations then we will be able to simulate any of theses systems.The objective is to write a program that solves the following ODE. This ODE represents the equation of motion of a simple pendulum with damping In the above equation,g = gravity in m/s2,L = length of the pendulum in m,m = mass of the ball in kg,b=damping coefficient.Write a program in Matlab\Octave that will simulate the pendulum motion, just like the one shown in the start of this challenge.use,L=1 metre,m=1 kg,b=0.05.g=9.81 m/s2.
clear all
close all
clc
%data
b=0.05;
g=9.81;
l=1;
m=1;
x0=0;
y0=0;
ct=1;
%initial condition
theta_0=[0;3];
% time_plot
t_span=linspace(0,20,500);
%solve_ode
[t,result]=ode45(@(t,theta) ode_func(t,theta,b,g,l,m),t_span,theta_0);
plot(t,result(:,1))
hold on
plot(t,result(:,2))
xlabel('plot')
ylabel('plot')
%pendulum simulation using ode
for i=1:length(result)
d=result(i,1);
%Defining x and y coordinates
x1=-l*sin(d);
y1=-l*cos(d);
hold on
plot([x0 x1],[y0 y1],'linewidth',4);
plot(x1,y1,'-o','markersize',30,'markeredgecolor','g','markerfacecolor',[0.5 0.5 0.5]);
plot(x0,y0,'-o','markersize',3,'markeredgecolor','g','markerfacecolor',[0.5 0.5 0.5]);
axis([-2 2 -2 2]);
pause(0.01);
M(ct)=getframe(gcf)
ct=ct+1;
clf()
end
%animation
movie(M);
videofile=videowriter('pendulum.avi','uncompressed AVI');
open(videofile)
writevideo(videofile,M)
close(videofile)
Function Code for ode_funcfunction createfigure(Parent1) %CREATEFIGURE(PARENT1) % PARENT1: matlab.graphics.primitive.world.quadrilateral parent % Auto-generated by MATLAB on 16-Sep-2018 10:48:20 % Create figure figure1 = figure; % Create axes axes('Parent',figure1); % Create matlab.graphics.primitive.world.Quadrilateral matlab.graphics.primitive.world.Quadrilateral('Parent',Parent1,... 'ColorBinding','interpolated',... 'ColorType','texturemapped',... 'ColorData',[1 1 0 0;0 1 1 0],... 'VertexData',[0 560 560 0;0 0 420 420;0 0 0 0]);
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