Here is my code
axis([0 5 -30 30]);
c=0;
theta=pi/6;
dt=1e-5;
nstep=round(5/dt);
stheta=0;
x1=theta;
x2=stheta;
dx1=x2;
dx2=-c*x2-21.791*sin(x1);
X=zeros(2,nstep);
V=zeros(2,nstep);
t=0:dt:(nstep-1)*dt;
tic
X(:,1)=[x1;x2];
V(:,1)=[dx1;dx2];
for i=2:(nstep)
X(:,i)=(dt*(V(:,i-1)))+X(:,i-1);
V(:,i)=[X(2,i);-c*X(2,i)-21.791*X(1,i)];
end
toc
plot(t,(180/pi)*X(1,:))
figure
plot(t,X(2,:))
In the above case I am using tic before X(:,1)=[x1;x2] and in the code below I am using tic before the for loop.
axis([0 5 -30 30]);
c=0;
theta=pi/6;
dt=1e-5;
nstep=round(5/dt);
stheta=0;
x1=theta;
x2=stheta;
dx1=x2;
dx2=-c*x2-21.791*sin(x1);
X=zeros(2,nstep);
V=zeros(2,nstep);
t=0:dt:(nstep-1)*dt;
X(:,1)=[x1;x2];
V(:,1)=[dx1;dx2];
tic
for i=2:(nstep)
X(:,i)=(dt*(V(:,i-1)))+X(:,i-1);
V(:,i)=[X(2,i);-c*X(2,i)-21.791*X(1,i)];
end
toc
plot(t,(180/pi)*X(1,:))
figure
plot(t,X(2,:))
But the time required in 1st case is less than that required in the second case and is varying. Why is it so I have plotted the histogram for both the case.
The code for histogram is
axis([0 5 -30 30]);
c=0;
theta=pi/6;
dt=1e-5;
nstep=round(5/dt);
stheta=0;
x1=theta;
x2=stheta;
dx1=x2;
dx2=-c*x2-21.791*sin(x1);
X=zeros(2,nstep);
V=zeros(2,nstep);
t=0:dt:(nstep-1)*dt;
comp_time = [];
for j=1:50
tic
X(:,1)=[x1;x2];
V(:,1)=[dx1;dx2];
for i=2:(nstep)
X(:,i)=(dt*(V(:,i-1)))+X(:,i-1);
V(:,i)=[X(2,i);-c*X(2,i)-21.791*X(1,i)];
end
comp_time = [comp_time,toc];
end
hist(comp_time);
title('Before X(:,1)=[x1;x2]');
comp_time = [];
for j=1:50
X(:,1)=[x1;x2];
V(:,1)=[dx1;dx2];
tic
for i=2:(nstep)
X(:,i)=(dt*(V(:,i-1)))+X(:,i-1);
V(:,i)=[X(2,i);-c*X(2,i)-21.791*X(1,i)];
end
comp_time = [comp_time,toc];
end
figure;
hist(comp_time);
title('Before for i=2:(nstep)');