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

1 次查看(过去 30 天)
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?

采纳的回答

Titus Edelhofer
Titus Edelhofer 2015-3-31
Hi,
slightly less ugly:
sum(v==2)
Titus

更多回答(1 个)

Stephen23
Stephen23 2015-3-31
编辑:Stephen23 2015-3-31
sum(v==2)
nnz(v==2)

类别

Help CenterFile Exchange 中查找有关 Matrix Indexing 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by