You can also use the sparse
function to do the counting:
% 100000x1 vector of integers in the range [1,100]
A = randi([1 100], [100000 1]);
% 100x1 array of counts
n = full(sparse(A, 1, 1, 100, 1));
As others have shown, this should give the same result as:
n = histc(A, 1:100);
or:
n = accumarray(A, 1, [100 1]);
(note that I explicitly specify the size in the sparse
and accumarray
calls. That's because if for a particular vector A
values didn't go all the way up to 100, then the counts array n
will be shorter than 100 in length).
All three methods are in fact mentioned in the tips section of the accumarray
doc page, which is the most flexible of all three.
The behavior of accumarray
is similar to that of the histc
function.
Both functions group data into bins.
histc
groups continuous values into a 1-D range using bin edges.
accumarray
groups data using n-dimensional subscripts.
histc
returns the bin counts using @sum
.
accumarray
can apply any function to the bins.
You can mimic the behavior of histc
using accumarray
with val = 1
.
The sparse
function also has accumulation behavior similar to that of accumarray
.
sparse
groups data into bins using 2-D subscripts, whereas accumarray
groups data into bins using n-dimensional subscripts.
sparse
adds elements that have identical subscripts into the output. accumarray
adds elements that have identical subscripts into
the output by default, but can optionally apply any function to the bins.