## Count number of specific values in matrix

on 2 May 2012

### Walter Roberson (view profile)

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?

## Products

No products are associated with this question.

on 2 May 2012

sum(m(:) == 4)

### Kye Taylor (view profile)

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()

### Sean de Wolski (view profile)

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)

#### Join the 15-year community celebration.

Play games and win prizes!

MATLAB and Simulink resources for Arduino, LEGO, and Raspberry Pi