Want to limit the lines of output. (for example, output after every 1000 iterations)
9 views (last 30 days)
Show older comments
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']
1 Comment
Image Analyst
on 27 Nov 2011
Why is "out" outside your loop? Do you want to break out of the loop when i = 1000? If you want to continue the loop you should put it inside the loop like Sven showed you.
Accepted Answer
Sven
on 27 Nov 2011
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
8 Comments
Sven
on 28 Nov 2011
Oh, that's easy then... I've edited the answer to print just one line ... ie, "out(i,:)" instead of "out(i-24:i,:)"
The reason the original program was slow was that *every* time the loop was run, the size of "out" (and "t" and "x" and "xdot") grew. This means that MATLAB kept on making new space in memory for a 99-by-4 array, 100-by-4 array, 101-by-4 array, etc, all the way up to 25000. That's a lot of "finding and allocating new space for a slightly different array". See the help docs for the word "preallocation".
If the question's all done, hit the "accept" button. Cheers,
Sven.
Sven
on 28 Nov 2011
And just to clarify, the if-stament with mod in the original program was displaying *all* of "out" each time it was reached, rather than just some subset of "out".
More Answers (0)
See Also
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!