Can I use UNIQUE to get a count of the number of times each element is repeated?
219 views (last 30 days)
Show older comments
MathWorks Support Team
on 14 Apr 2011
Answered: Lola Davidson
on 6 Sep 2022
I would like to know if the UNIQUE function has the capability of returning the number of times each element appears in an array.
Accepted Answer
MathWorks Support Team
on 14 Apr 2011
The ability to return the count of each unique element is not available in the UNIQUE function in MATLAB.
To work around this issue, use the ARRAYFUN function to test each element of an array, determining the number of times each element is equal to an element of original vector.
For example:
a = [12 34 78 8 12 3 34 34];
c = arrayfun(@(x)length(find(a == x)), unique(a), 'Uniform', false);
cell2mat(c)
1 Comment
Zenin Easa Panthakkalakath
on 21 Apr 2022
Edited: Zenin Easa Panthakkalakath
on 21 Apr 2022
Ideally, the following histogram based method should work for this purpose and I wanted to use that as it is faster. However, it doesn't work for large data as there is a limit to the maximum number of bins which is
or
.


c = histcounts(sort(a), 'BinMethod', 'integers');
c(c == 0) = [];
A workaround that I found for the same is to use categorical arrays.
c1 = histcounts(categorical(a));
c1(c1 == 0) = [];
More Answers (1)
Lola Davidson
on 6 Sep 2022
>> a = [12 34 78 8 12 3 34 34]';
>> [counts, groupnames] = groupcounts(a)
counts =
1
1
2
3
1
groupnames =
3
8
12
34
78
0 Comments
See Also
Categories
Find more on Shifting and Sorting Matrices in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!