Corresponding list of number of occurrences for each vector element

Alec Jacobson

January 29, 2014

weblog/

If I have a n-long vector x and I'd like a new n-long vector counts that contains for each element in x the number of times the same value occurs in x (aka the value frequency), then the following matlab code will compute counts.

[u,~,ic] = unique(x);
counts = histc(x,u);
counts = counts(ic);

The last step is essential to distribute the counts in the same order and length of x.