How do I exit a for loop after logical index is found true in an array?

조회 수: 9 (최근 30일)
I would like to exit a loop if the result is set to true in the for loop. But it always returns false if I use 'continue'. How do I resolve this?
% check if trajectory goes through the zone
result = false;
for i = 1:length(xNormalized)
if (xNormalized(i) > xEdge(1) && xNormalized(i) < xEdge(2)) && ...
(yNormalized(i) > yEdge(1) && yNormalized(i) < yEdge(2))
result = true;
end
% continue;
end

채택된 답변

VBBV
VBBV 2022년 12월 4일
use inside the if-end statement
% check if trajectory goes through the zone
result = false;
for i = 1:length(xNormalized)
if (xNormalized(i) > xEdge(1) && xNormalized(i) < xEdge(2)) && ...
(yNormalized(i) > yEdge(1) && yNormalized(i) < yEdge(2))
result = true
break % use inside the if - condition
end
end
  댓글 수: 2
VBBV
VBBV 2022년 12월 4일
편집: VBBV 2022년 12월 4일
If you use outside the if condition the result state may not be saved to true if this for loop is nested inside another loop which means it will restore the result state back to false. I presume, this for loop is present inside another loop, thats why result flag is being set to false again.
If you want to avoid reuslt to set false, you need to place the result flag outside of all nested loops.
Struggling in MATLAB
Struggling in MATLAB 2022년 12월 4일
Thank you! I was using outside the if statement and that did not work. It works if I use inside if as you suggested. By the way, this for loop is the outermost loop.

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

추가 답변 (1개)

Steven Lord
Steven Lord 2022년 12월 4일
continue exits the current iteration and proceeds to the next iteration.
break exits the loop entirely.
  댓글 수: 1
Struggling in MATLAB
Struggling in MATLAB 2022년 12월 4일
Both 'break' and 'continue' sets the result to default 'false'. I tried with both of them.

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

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

태그

제품


릴리스

R2022b

Community Treasure Hunt

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

Start Hunting!

Translated by