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

1 view (last 30 days)
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

Accepted Answer

VBBV
VBBV on 4 Dec 2022
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 Comments
Struggling in MATLAB
Struggling in MATLAB on 4 Dec 2022
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.

Sign in to comment.

More Answers (1)

Steven Lord
Steven Lord on 4 Dec 2022
continue exits the current iteration and proceeds to the next iteration.
break exits the loop entirely.
  1 Comment
Struggling in MATLAB
Struggling in MATLAB on 4 Dec 2022
Both 'break' and 'continue' sets the result to default 'false'. I tried with both of them.

Sign in to comment.

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Tags

Products


Release

R2022b

Community Treasure Hunt

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

Start Hunting!