Count the number of same elements in an array
332 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
luca
am 10 Sep. 2019
Bearbeitet: Vitek Stepien
am 14 Aug. 2021
Hi given a vector
V = [ 1 2 4 3 4 2 3 5 6 4 5 6 8 4 2 3 5 7 8 5 3 1 3 5 7 8 9 5 3 2 4 6 7 8]
I would like to count how many times the value 1,2,3,4,5,6,7,8,9 are repeated inside V, and obtain a vector that report this values:
C = [2 4 6 5 6 3 3 4 1]
where 1 is repeated 2 times, 2 is repetead 4 times, 3 is repeated 6 times and so on..
0 Kommentare
Akzeptierte Antwort
madhan ravi
am 10 Sep. 2019
Bearbeitet: madhan ravi
am 10 Sep. 2019
[~,~,ix] = unique(V);
C = accumarray(ix,1).'
Weitere Antworten (3)
Vitek Stepien
am 14 Aug. 2021
Bearbeitet: Vitek Stepien
am 14 Aug. 2021
I found this function extremely useful, and doing exactly what you need:
V = [ 1 2 4 3 4 2 3 5 6 4 5 6 8 4 2 3 5 7 8 5 3 1 3 5 7 8 9 5 3 2 4 6 7 8];
[gc,grps] = groupcounts(V'); % <- need column vector here
grps'
gc'
Where grps lists the unique values in order, and gc provides the count of each unique values found in v.
This is very similar to madhan ravi's accumarray, but even simpler.
P.S. I turned gc and grps into row vectors only for compactness of the post, it's purely aesthetical. However groupcounts requires a column vector, not a row.
0 Kommentare
Hugo Diaz
am 28 Nov. 2020
I use sparse(V(:),V(:), 1) for large arrays with missing indices.
0 Kommentare
Siehe auch
Kategorien
Mehr zu Multidimensional Arrays finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!