Does anyone know how to count the number of times a value appears in a matrix?
For example, if I have a 1500 x 1 matrix M
(vector) which stores the values of weekdays (1 - 7), how could I count how many Sundays (1), Mondays(2), ... , Saturdays(7) are stored in M
?
Use nnz instead of sum. No need for the double call to collapse matrices to vectors and it is likely faster than sum.
Doc
assume w contains week numbers ([1:7])
if you do not know the range of numbers in M:
It is such as a SQL Group by command!
Here's a list of all the ways I could think of to counting unique elements:
Option 1: tabulate
Option 2: hist/histc
Option 3: accumarray
Option 4: sort/diff
Option 5: arrayfun
Option 6: bsxfun
Option 7: sparse
this would be perfect cause we are doing operation on matrix, and the answer should be a single number
Have a look at Determine and count unique values of an array.
Or, to count the number of occurrences of
5
, simply doThis is a very good function file available on Matlab Central File Exchange.
countmember.m link
This function file is totally vectorized and hence very quick. Plus, in comparison to the function being referred to in aioobe's answer, this function doesn't use the accumarray function, which is why this is even compatible with older versions of Matlab. Also, it works for cell arrays as well as numeric arrays.
SOLUTION : You can use this function in conjunction with the built in matlab function, "unique".
occurance_count will be a numeric array with the same size as that of unique(M) and the different values of occurance_count array will correspond to the count of corresponding values (same index) in unique(M).