Is there a simpler way to count the number of elements of a vector that is equal to a given number?

4 visualizaciones (últimos 30 días)
I have a vector v and a number a. I want to count the number of elements in v that is equal to a. What is a simpler way to do this?

Respuesta aceptada

Walter Roberson
Walter Roberson el 29 de Jul. de 2020
nnz(v == a)
You will probably also see
sum(v == a)
The nnz() version works for multidimensional arrays as well, whereas the sum() version would count along the first non-scalar dimension.
  3 comentarios
Image Analyst
Image Analyst el 29 de Jul. de 2020
If they're floating point values that are not integers or a power of 2, then you might need to use ismembertol() to do the comparison.

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Sparse Matrices en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by