필터 지우기
필터 지우기

how to exit a for loop if a condition is true?!

조회 수: 89 (최근 30일)
Ano
Ano 2017년 5월 16일
댓글: KSSV 2017년 5월 16일
hello! I would like to exit a for lopp is a condition is true but my code doesn't seem to work, could you help me to figure out where is the problem?! Thank you best regards!
a= [ 1 2 3 5 8 6 8 8 2 8 2 8 2 8 2 1 nan 45 56 89];
for i= 1:length(a)
indx1 = find(isnan(a));
if ~isempty (indx1)
L = i ;
return
end
end
  댓글 수: 2
KSSV
KSSV 2017년 5월 16일
But what's the purpose of the code?
Ano
Ano 2017년 5월 16일
I need to get the index where the first nan is encountered and stop the loop as the main code should look for a critical point where the behavior starts to change

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

답변 (2개)

KSSV
KSSV 2017년 5월 16일
a= [ 1 2 3 5 8 6 8 8 2 8 2 8 2 8 2 1 nan 45 56 89];
for i= 1:length(a)
indx1 = find(isnan(a));
if ~isempty (indx1)
L = i ;
break
end
end
  댓글 수: 2
Ano
Ano 2017년 5월 16일
I have tried to use break but my L is always = 1, do you have any other suggestions ??!
KSSV
KSSV 2017년 5월 16일
YOu can simply use
find(isnan(a))

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


Walter Roberson
Walter Roberson 2017년 5월 16일
L = find(isnan(a), 1, 'first');
with no loop.
You are testing the same vector of values each time, all of a, so your result would always be either 1 or not found.

카테고리

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