This nested for loop goes on forever?

1 view (last 30 days)
Blah Blah
Blah Blah on 20 Sep 2012
Question: A ball is launched from a height of 12m. It should land in a pool that has a length of 22m and is 9m away from the wall. Find the minimum and maximum initial velocities for the ball to land in the pool. The ramp is angled at 1 radian such that vy = 0.54v and vx = 0.84v at time zero. The ball will not be airborned for more than 3 seconds.
So I tried to write a loop for it. My nested for loop goes on forever...can someone please help?
s= 'DEAD';
k = 'ALIVE';
v0=0:0.01:100;
t=0:0.01:3;
for r=1:length(v0);
v00=v0(r);
vxx=v0(r)*0.84;
vyy=v0(r)*0.54;
pxi=vxx.*t;
for j = 1:length(pxi);
if pxi(j)<9;
fprintf('%s', s);
elseif pxi(j)>31;
fprintf('%s', s);
else
fprintf('%s', k);
end;
j=j+1;
end;
end;
PLEASE help! I think my approach may be wrong. If anyone can provide some pseducode :/ I suck at matlab!

Answers (2)

Walter Roberson
Walter Roberson on 20 Sep 2012
Your loop does not go on forever. On the other hand, length(v0) will be over 100/0.01 which is 10000, and those 10000 velocities will each loop over the 301 times, so your inner loop is going to execute over 3 million times.
  2 Comments
Blah Blah
Blah Blah on 20 Sep 2012
Is there another way of doing this? ><'
Walter Roberson
Walter Roberson on 20 Sep 2012
Create a function that determines the distance for a given velocity. Find the zero of (dist(velocity) - 9)^2 to determine the close end. Find the zero of (dist(velocity) - 31)^2 to determine the further end.

Sign in to comment.


Jan
Jan on 20 Sep 2012
Edited: Jan on 20 Sep 2012
The code should be cleaned up a bit. E.g. the loop counter should not be incremented manually inside the loop:
for j = 1:10
disp(j)
j = j + 1; % *useless* and therefore a waste of time
end
v00 and vyy are never used in your code, so omit them.
Suggestion:
s = 'DEAD';
k = 'ALIVE';
v0 = 0:0.01:100;
t = 0:0.01:3;
for r = 1:length(v0)
vxx = v0(r) * 0.84;
pxi = vxx .* t;
for j = 1:length(pxi)
if pxi(j) >= 9 && pxi(j) <= 31
fprintf('%s', k);
else
fprintf('%s', s);
end
end
end
Or even shorter:
s = {'DEAD', 'ALIVE'};
v0 = 0:0.01:100;
t = 0:0.01:3;
for r = 1:length(v0)
pxi = v0(r) * 0.84 .* t;
index = (pxi >= 9 && pxi <= 31) + 1;
fprintf('%s\n', s{index});
end
And a tick faster:
index = (abs(20 - pxi) <= 11) + 1;
However, you will still have 3 million strings in the command window and I cannot imagine a situation where this is useful.

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!