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

조회 수: 4 (최근 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 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