MATLAB Answers

Count number of specific values in matrix

5,934 views (last 30 days)
I have a large matrix, m, and am trying to count the number of a specific value (i.e. How many indexes are of the value 4?)
I tried using
val = sum(m == 4);
but I end up with val being a matrix/vector of numbers. I assume these numbers are from each column and should be added together for the total, so I tried another
num = sum(val == 4);
but then I just end up with another vector/matrix.
How can I do it?

  0 Comments

Sign in to comment.

Accepted Answer

Walter Roberson
Walter Roberson on 2 May 2012
sum(m(:) == 4)

  2 Comments

Romy Wolstencroft
Romy Wolstencroft on 22 Aug 2019
This worked perfectly for me. Thank you
MathWorks Support Team
MathWorks Support Team on 2 Sep 2020
An alternative syntax available in R2018b or later is sum(m==4,'all'). But for this simple problem colonizing the input with m(:) is likely to be faster.

Sign in to comment.

More Answers (5)

Kye Taylor
Kye Taylor on 2 May 2012
Try this:
numberOfNonZeros = nnz(m==4);
Using nnz is more efficient than converting logicals to numeric, which is required to apply sum()

  1 Comment

Walter Roberson
Walter Roberson on 22 Aug 2019
In the test I just did, the timings of sum() vs nnz() could not consistently tell the two cases apart. nnz() might possibly have been slightly faster, but the range of timings showed so much overlap that no real conclusion could be reached. It would make sense that nnz() could be faster, but I can't prove it at the moment. sum() on a large enough array could be dispatched to LAPACK after all.

Sign in to comment.


Sean de Wolski
Sean de Wolski on 2 May 2012
This could be done easily with histc() and unique() to get the number of each value:
uv = unique(x);
n = histc(x,uv);
Or with unique() and accumarray():
[uv,~,idx] = unique(x);
n = accumarray(idx(:),1)

  0 Comments

Sign in to comment.


ntsh kr
ntsh kr on 12 Oct 2017
Edited: ntsh kr on 12 Oct 2017
>> a
a =
5 5 5 5 5 5 5 6 9 96
5 3 9 5 2 7 5 6 2 1
8 3 6 9 8 7 5 1 6 9
>> ans1=sum(a==5)
ans1 =
2 1 1 2 1 1 3 0 0 0
>> b=sum(ans1)
b =
11

  1 Comment

Sign in to comment.


dipanka tanu sarmah
dipanka tanu sarmah on 11 Nov 2017
along with this if you want to count the number of NaN ,(if there any) use nnz(isnan(m))

  0 Comments

Sign in to comment.


vimal kumar chawda
vimal kumar chawda on 18 May 2020
But if we want ot do for NaN and any numeric value in large matrix then ?
ans1=sum(a==5) so at this my value is numerical (which is not same all time) and other is NaN which is common. But i need to count only numerical value at particular value of x.,x2,x3...............x7000 which is on y axis.
-How many times y appear on the at particular value of x?

Community Treasure Hunt

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

Start Hunting!