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?

추가 답변 (1개)

Stephen23
Stephen23 2015년 3월 31일
편집: Stephen23 2015년 3월 31일
sum(v==2)
nnz(v==2)

댓글 수: 2

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?

댓글을 달려면 로그인하십시오.

카테고리

도움말 센터 및 File Exchange에서 Matrix Indexing에 대해 자세히 알아보기

질문:

2015년 3월 31일

편집:

2015년 3월 31일

Community Treasure Hunt

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

Start Hunting!

Translated by