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
?
this would be perfect cause we are doing operation on matrix, and the answer should be a single number
sum(sum(matrix==value))
Here's a list of all the ways I could think of to counting unique elements:
M = randi([1 7], [1500 1]);
t = tabulate(M);
counts1 = t(t(:,2)~=0, 2);
counts2_1 = hist( M, numel(unique(M)) );
counts2_2 = histc( M, unique(M) );
counts3 = accumarray(M, ones(size(M)), [], @sum);
%# or simply: accumarray(M, 1);
[MM idx] = unique( sort(M) );
counts4 = diff([0;idx]);
counts5 = arrayfun( @(x)sum(M==x), unique(M) );
counts6 = sum( bsxfun(@eq, M, unique(M)') )';
counts7 = full(sparse(M,1,1));
assume w contains week numbers ([1:7])
n = histc(M,w)
if you do not know the range of numbers in M:
n = histc(M,unique(M))
It is such as a SQL Group by command!
Use nnz instead of sum. No need for the double call to collapse matrices to vectors and it is likely faster than sum.
nnz(your_matrix == 5)
This is a very good function file available on Matlab Central File Exchange.
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 = countmember(unique(M),M)
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).
One way you can perform this operation for all the values 1 through 7 at once is to use the function ACCUMARRAY:
>> M = randi(7,1500,1); %# Some random sample data with the values 1 through 7
>> dayCounts = accumarray(M,1) %# Will return a 7-by-1 vector
dayCounts =
218 %# Number of Sundays
200 %# Number of Mondays
213 %# Number of Tuesdays
220 %# Number of Wednesdays
234 %# Number of Thursdays
219 %# Number of Fridays
196 %# Number of Saturdays
Source: Stackoverflow.com