Is there a simpler way to count the number of elements of a vector that is equal to a given number?

4 views (last 30 days)
I have a vector v and a number a. I want to count the number of elements in v that is equal to a. What is a simpler way to do this?

Accepted Answer

Walter Roberson
Walter Roberson on 29 Jul 2020
nnz(v == a)
You will probably also see
sum(v == a)
The nnz() version works for multidimensional arrays as well, whereas the sum() version would count along the first non-scalar dimension.
  3 Comments
Image Analyst
Image Analyst on 29 Jul 2020
If they're floating point values that are not integers or a power of 2, then you might need to use ismembertol() to do the comparison.

Sign in to comment.

More Answers (0)

Categories

Find more on Sparse Matrices in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!