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.

1 visualización (últimos 30 días)
for ii = 1:length(readings)
if readings(ii) > 100
break;
end
end
fprintf('First reading above 100 is at index %d.\n', ii);

Respuesta aceptada

Alan Stevens
Alan Stevens el 25 de Mayo de 2020
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 comentarios
Randall Ang
Randall Ang el 25 de Mayo de 2020
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?

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Loops and Conditional Statements en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by