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

3 次查看(过去 30 天)
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 个评论
James Tursa
James Tursa 2016-6-22
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 2016-6-22
"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.

请先登录,再进行评论。

采纳的回答

dpb
dpb 2016-6-23
编辑:dpb 2016-6-23
"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 个评论
Travis Yeager
Travis Yeager 2016-6-23
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!

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by