Which is the shortest way to count elements in the set of vector components?

v = [1,3,4,1,2,2,1,2,3,2,2,2,1,4]
I would like to count the twos.
I have this ugly solution:
length(v(v==2))
are there any shorter solution?

Más respuestas (1)

Stephen23
Stephen23 el 31 de Mzo. de 2015
Editada: Stephen23 el 31 de Mzo. de 2015
sum(v==2)
nnz(v==2)

2 comentarios

The nnz solution will tend to be slightly the fastest.
Stephen23
Stephen23 el 31 de Mzo. de 2015
Editada: Stephen23 el 31 de Mzo. de 2015
@John D'Errico: Is this generally true, or only for specific use cases?

Iniciar sesión para comentar.

Categorías

Más información sobre Creating and Concatenating Matrices en Centro de ayuda y File Exchange.

Etiquetas

Preguntada:

el 31 de Mzo. de 2015

Editada:

el 31 de Mzo. de 2015

Community Treasure Hunt

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

Start Hunting!

Translated by