Is it possible to put an if statement into a for loops counter?

3 views (last 30 days)
I need a counter that stops at one of two values, which ever is reached first.
Example
for r=1: (if statement here)
for c=1: (if statement here)
do things
end
end
I've tried achieving what I need with two nested while loops:
while r < r1 && r < r2
r=r+1
while r < r1 && r < r2
c=+c+1
if condition
else
stuff
end
end
end
but the first while loop just counts through all it's iterations and then moves onto the 2nd while loop, rather than counting once then moving into the 2nd while loop until that condition is met.
  2 Comments
James Tursa
James Tursa on 22 Jun 2016
It isn't clear to me yet how you want the counters to behave. Do you want r to count until a condition is met, and then for that r value count c until a different condition is met? Or do you want r and c to count together somehow until a condition is met? Once the condition(s) are met, do you continue counting both counters or does one of them start over? etc.
dpb
dpb on 22 Jun 2016
"first while loop just counts through all its iterations and then moves onto the 2nd while loop rather than counting once then moving into the 2nd while..."
That's simply not so...the first loop iterates once, enters the second which is infinite since it never increments the test variable r.

Sign in to comment.

Accepted Answer

dpb
dpb on 23 Jun 2016
Edited: dpb on 23 Jun 2016
"need a counter that stops at one of two values, which ever is reached first."
while r < r1 && r < r2
r=r+1
while r < r1 && r < r2
...
This doesn't need a nested loop or any other exotic IF cases, simply
for r=initialCount:min(r1,r2)
...
If r1,r2 can change inside the loop, then you need a while construct instead because the for iteration limits are set on entry to the construct and not altered even if the variables are.
>> r1=3;
>> for r=1:r1
disp([r r1])
if r==1, r1=5; end
end
1 3
2 5
3 5
>>
As you can see, the loop only ran 3 iterations, not 5.
Also see
doc break % to terminate a loop
It can, of course, be included in an if construct that is a complex as needed on any variables needed.
  1 Comment
Travis Yeager
Travis Yeager on 23 Jun 2016
Thank you very much! Was not aware of the min function. My variables are not changing in the loop but some other conditions are that depend on if it should go to r1 or r2. Thank you!

Sign in to comment.

More Answers (0)

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!