필터 지우기
필터 지우기

exit from a nested loop

조회 수: 1 (최근 30일)
Riccardo Tronconi
Riccardo Tronconi 2021년 6월 7일
편집: Jan 2021년 6월 7일
Hi guys I have a problem with a inner loop:
Once the break command is read I correctly exit from the inner while loop but afterwards it does not increment i and consequently I cannot re-entering in the while loop.
How can I do that?
I guess break it is not the right command
for i=1:length(A)
counter2=0;
Xtot2=0;
Ytot2=0;
Xmean2 = 0;
Ymean2 = 0;
j=1;
while j <= length(F2)
if statement
break
end
if statement
counter2= counter2+1;
Xtot2= Xtot2 + F2{j,3};
Ytot2= Ytot2 + F2{j,4};
Xmean2 = (Xtot2/counter2);
Ymean2= (Ytot2/counter2);
H12{i,6}= Xmean2;
H12{i,7}= Ymean2;
end
end
end
  댓글 수: 2
Julius Muschaweck
Julius Muschaweck 2021년 6월 7일
You may have another problem:
for i = 1:3
j = 0;
fprintf('i == %g\n',i);
while j <= i
j = j + 1;
fprintf('j == %g\n',j);
if j == 2
fprintf('break\n',j);
break
end
end
end
correctly tells me
i == 1
j == 1
j == 2
break
i == 2
j == 1
j == 2
break
i == 3
j == 1
j == 2
break
Riccardo Tronconi
Riccardo Tronconi 2021년 6월 7일
Yes! that's what I'm looking for!!
The other problem is that counter2 never returns to 0 whenever "break" command is read...
If I copy and past my code would you mind try to run on your side?

댓글을 달려면 로그인하십시오.

채택된 답변

Jan
Jan 2021년 6월 7일
편집: Jan 2021년 6월 7일
"I correctly exit from the inner while loop but afterwards it does not increment i"
Why do you assume this? The outer loop is not influenced by breaking the inner loop.
"counter2 never returns to 0 whenever "break" command is read..."
Of course the break command breaks the inner loop and does not reset counter2 to 0. But this reset is does, when the outer loop runs its next iteration.
As far as I can see, your assumptions are not correct. USe the debugger to step through your code line by line to see, what's going on.
Note that your inner loop does not increment j anywhere. Therefore the condition "while j <= length(F2)" does not seem to be correct.

추가 답변 (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