MATLAB: Want to limit the lines of output. (for example, output after every 1000 iterations)

number of iterations

time = 0;
tstop=input('enter tstop now');
m=input('enter value of m now');
k= input('enter value of k now');
b= input('enter b value now');
dt=input(' enter value of time step now');
nstep=input('enter value of nstep');
pos=input('enter starting position now');
vel=input('enter starting velocity now');
i=1;
j=1;
while time < tstop
t(i) = time;
xdot(i) = vel;
x(i) = pos;
acc= -(k/m)*pos -(b/m)*vel;
x2dot(i)=acc;
vel = vel + acc*dt;
pos = pos + vel*dt;
time = time+dt;
i=i+1;
end
out=[t',x2dot',xdot',x']

Best Answer

Hi Brian, your loop has a number of places where arrays are growing inside a loop. I believe this is the main reason why your code runs for 25 seconds. Things will run much faster if you preallocate. In fact, try the code below which should be almost instantaneous:
tstop=25; dt=0.001;
m=2; k=5; b=1;
pos=20; vel=3;
time = 0:dt:tstop;
out = zeros(length(time),4); % This is the big time-saver
out(:,1) = time';
for i = 1:length(time)
acc= -(k/m)*pos -(b/m)*vel;
out(i,2:4) = [acc vel pos];
vel = vel + acc*dt;
pos = pos + vel*dt;
end
Now, there are further speed-ups that could be made, but I've tried to keep the code similar to your original.
If you need the last row displayed to the screen once every 1000 iterations, then add this small if-statement inside the for-loop:
if mod(i,1000)==0
disp(out(i,:))
end
I hope that answers the question