Azzera filtri
Azzera filtri

how i break nested for loop

38 visualizzazioni (ultimi 30 giorni)
m. muner
m. muner il 10 Apr 2016
Commentato: m. muner il 11 Apr 2016
hello i have three loops and two conditions and flag and i'm trying to use break statement to break the loop after the second condition true but what i get two variables having same value which is impossible what wrong
temp=0;cov=0;sov=0;
for I=1:30
for J=1:30
for N=1:x
dis=sqrt(((I-test_ary(N,2)).^2)+((J-test_ary(N,1)).^2));
if(dis<=r)
if (temp==0)
cov=cov+1;
temp=1;
else
if(temp==1)
sov=sov+1;
temp=0;
break
end
end
end
end
end
end
  2 Commenti
dpb
dpb il 10 Apr 2016
What is the expected result you're looking for? The first break will only terminate the innermost loop (on N) so the outer loops will still run to completion (which, of course, will start the innermost loop over again each pass). And, of course, since you reset temp in the else clause, the cov accumulator may increment again.
A description of the objective you're trying to achieve might help.
m. muner
m. muner il 11 Apr 2016
well i have gird of small squares and circles with radius distributed in the area and I'm measuring the distance between each circle and square if the distance less than r the cov increase if two circles have distance less than r with the same square the sov increase and the loop is braked so sov should be smaller than cov not equal

Accedi per commentare.

Risposta accettata

Image Analyst
Image Analyst il 10 Apr 2016
Set a flag:
finishNow = false; % Call this before the loop to initialize.
Then in the loop:
finishNow = true;
Right before the "ends" for i and j, break if the flag is set:
if finishNow
break
end
end % of i or j loop
You will need that twice - once for the i loop and once for the j loop.

Più risposte (0)

Categorie

Scopri di più su Loops and Conditional Statements in Help Center e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by