How do I call the elements in an array to be counted?

1 visualización (últimos 30 días)
Soph E
Soph E el 26 de Nov. de 2020
Comentada: Image Analyst el 26 de Nov. de 2020
I am trying to create a while loop which loops over the elements in the array sumCheck and stops looping when it reaches an element that is greater than 9. I also want to count how many times the loop loops, so I've used count.
count = 0
while sumCheck <= 9 && count<=length(sumCheck)
count = count + 1
end
count
So far I've written this, but I feel like I'm missing something. I'm not sure how to call for all the elements in sumCheck to be less than 9.

Respuestas (2)

Image Analyst
Image Analyst el 26 de Nov. de 2020
Try this
count = 1;
while sumCheck(count) <= 9
count = count + 1
end
fprintf('Exited loop when count = %d and sumCheck(%d) = %f.\n', count, count, sumCheck(count))
  2 comentarios
Soph E
Soph E el 26 de Nov. de 2020
thank you. however it seems to stop at the element after the element of value of 9 instead of at the element of value 9 itself e.g. at 10 instead of 9?
Image Analyst
Image Analyst el 26 de Nov. de 2020
Yes, because you said "stops looping when it reaches an element that is greater than 9." so it will stop at 10. If you want the one before that, simply subtract 1 from count after the loop.
count = 1;
while sumCheck(count) <= 9
count = count + 1
end
fprintf('Exited loop when count = %d and sumCheck(%d) = %f.\n', count, count, sumCheck(count))
count = count - 1;
or change <= to <.

Iniciar sesión para comentar.


Ameer Hamza
Ameer Hamza el 26 de Nov. de 2020
You can do it without loop
count = find(sumCheck>9, 1) - 1;
  1 comentario
Soph E
Soph E el 26 de Nov. de 2020
thank you. but i am trying to use a while loop, specifically

Iniciar sesión para comentar.

Categorías

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

Etiquetas

Productos


Versión

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by