Another option for this situation is to use the function ACCUMARRAY, which wouldn't require that the list be sorted first. This is particularly useful if you were to have a set of numbers in item
that span a range of 1:N
, where N
is any integer value. Here's how it would work for your example:
item = [23; 23; 23; 22; 22; 20; 20]; %# A column vector of integers
counts = accumarray(item,1); %# Collect counts of each item into
%# a 23-by-1 array
The array counts
is a 23-by-1 array where the elements indexed by 23, 22, and 20 contain the counts 3, 2, and 2, respectively. All the other elements are 0 (i.e. there are no counts found for the numbers 1 through 19 or 21).
If you want to get a list of the unique values in item
and their corresponding counts, you can do this using the function UNIQUE:
>> uniqueValues = unique(item) %# Get the unique values in item
uniqueValues =
20
22
23
>> counts = counts(uniqueValues) %# Get just the counts for each unique value
counts =
2
2
3