Hi everyone, I have been trying to debug this for loop as it always retain the last value of the array even if none of the conditions meet for every element. For instance, using readings = [1 20 55 90], it will print that reading(4)>100.

조회 수: 2 (최근 30일)
for ii = 1:length(readings)
if readings(ii) > 100
break;
end
end
fprintf('First reading above 100 is at index %d.\n', ii);

채택된 답변

Alan Stevens
Alan Stevens 2020년 5월 25일
Try:
ix = 0;
for ii = 1:length(readings)
if readings(ii) > 100
ix = ii;
break;
end
end
fprintf('First reading above 100 is at index %d.\n', ix);
  댓글 수: 2
Randall Ang
Randall Ang 2020년 5월 25일
ahh, it works, thanks. very smart! so we initialise another variable and print it instead, since the for loops will cause ii to retain the last element if it does not break the if statement right?

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

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