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

2 views (last 30 days)
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?

Accepted Answer

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

More Answers (1)

Stephen23
Stephen23 on 31 Mar 2015
Edited: Stephen23 on 31 Mar 2015
sum(v==2)
nnz(v==2)

Community Treasure Hunt

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

Start Hunting!