# how i break nested for loop

74 views (last 30 days)
m. muner on 10 Apr 2016
Commented: m. muner on 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 CommentsShowHide 1 older comment
m. muner on 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

Image Analyst on 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.