Count number of specific values in matrix
4,124 views (last 30 days)
Corey Bullard on 2 May 2012
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?
More Answers (6)
Kye Taylor on 2 May 2012
numberOfNonZeros = nnz(m==4);
Using nnz is more efficient than converting logicals to numeric, which is required to apply sum()
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)
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))
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?
Patrick Benz on 2 Apr 2021
How can I count the values in the second column of an array depending on the values in the column?
I've got an array that looks something like that:
and I want to know how often there is a "1" or a "0" next to a "400" or next to the other values.
I tried it with this way https://de.mathworks.com/matlabcentral/answers/37196-count-number-of-specific-values-in-matrix#answer_46452
but this only gives me the total numbers of "1" and "0" and how often there is a 392 in the first column.