How can I count the occurrences of each element in a vector in MATLAB?
Afficher commentaires plus anciens
I would like to be able to return the count of occurences of each element in a vector.
For example if I have a vector:
x=[10 25 4 10 9 4 4]
I expect the result to be
y=[2 1 3 2 1 3 3].
Réponse acceptée
Plus de réponses (3)
Andrei Bobrov
le 14 Août 2014
[a,b] = histc(x,unique(x));
y = a(b);
1 commentaire
Andrei Bobrov
le 3 Août 2015
y = accumarray(x(:),1)
Razvan Carbunescu
le 9 Mai 2019
>> x=[10 25 4 10 9 4 4]';
>> grouptransform(x,x,@numel)
ans =
2
1
3
2
1
3
3
>>[GC,GR]=groupcounts(x)
GC =
3
1
2
1
GR =
4
9
10
25
4 commentaires
Razvan Carbunescu
le 5 Juin 2019
I'm not sure I understand the question Masoud. Multiple columns can be fed into groupcounts and it will count the occurances of each unique line but I don't know if that's what you're asking.
madhan ravi
le 5 Juin 2019
+1
Razvan Carbunescu
le 6 Juin 2019
For the example you gave above how does the solution look and what does 'similar number' for the first column mean?
Razvan Carbunescu
le 7 Juin 2019
This seems like a very different type of problem so unlikely the functions in this topic will help you directly. I'd post this question as a separate thread with the example input/output
Julian Hapke
le 1 Juin 2017
Modifié(e) : Julian Hapke
le 1 Juin 2017
here is another one:
sum(bsxfun(@eq,x,x'),1)
or if you want the output to be the same orientation as input
sum(bsxfun(@eq,x,x'),(size(x,2)==1)+1)
1 commentaire
Johannes Korsawe
le 1 Juin 2017
the second solution exhibits pathological tendencies...
Catégories
En savoir plus sur Data Type Identification dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!