how i break nested for loop
35 次查看(过去 30 天)
显示 更早的评论
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 个评论
dpb
2016-4-10
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.
采纳的回答
Image Analyst
2016-4-10
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.
0 个评论
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!