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

1 回表示 (過去 30 日間)
Mr M.
Mr M. 2015 年 3 月 31 日
編集済み: Stephen23 2015 年 3 月 31 日
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)
  2 件のコメント
John D'Errico
John D'Errico 2015 年 3 月 31 日
The nnz solution will tend to be slightly the fastest.
Stephen23
Stephen23 2015 年 3 月 31 日
編集済み: Stephen23 2015 年 3 月 31 日
@John D'Errico: Is this generally true, or only for specific use cases?

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeMatrix Indexing についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by