How do I exit a for loop after logical index is found true in an array?
6 次查看(过去 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
0 个评论
采纳的回答
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
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.
更多回答(1 个)
另请参阅
类别
在 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!