MATLAB Answers

1

Count number of specific values in matrix

Asked by Corey Bullard on 2 May 2012
Latest activity Edited by ntsh kr
on 12 Oct 2017 at 7:54

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

Log in to comment.

Tags

4 Answers

Answer by Walter Roberson
on 2 May 2012
 Accepted Answer

sum(m(:) == 4)

  0 Comments

Log in to comment.


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

  0 Comments

Log in to comment.


Answer by 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

Log in to comment.


Answer by ntsh kr
on 12 Oct 2017 at 7:06
Edited by ntsh kr
on 12 Oct 2017 at 7:54

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

  0 Comments

Log in to comment.


Discover MakerZone

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

Learn more

Discover what MATLAB® can do for your career.

Opportunities for recent engineering grads.

Apply Today

MATLAB Academy

New to MATLAB?

Learn MATLAB today!