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);
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
Best Answer