Filter löschen
Filter löschen

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

3 Ansichten (letzte 30 Tage)
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 Kommentare
James Tursa
James Tursa am 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 am 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.

Melden Sie sich an, um zu kommentieren.

Akzeptierte Antwort

dpb
dpb am 23 Jun. 2016
Bearbeitet: dpb am 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 Kommentar
Travis Yeager
Travis Yeager am 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!

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by