フィルターのクリア

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

3 ビュー (過去 30 日間)
Travis Yeager
Travis Yeager 2016 年 6 月 22 日
コメント済み: Travis Yeager 2016 年 6 月 23 日
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 Center および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by