How can I count the occurrences of each element in a vector in MATLAB?
Ältere Kommentare anzeigen
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].
Akzeptierte Antwort
Weitere Antworten (3)
Andrei Bobrov
am 14 Aug. 2014
[a,b] = histc(x,unique(x));
y = a(b);
1 Kommentar
Andrei Bobrov
am 3 Aug. 2015
y = accumarray(x(:),1)
Razvan Carbunescu
am 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 Kommentare
Razvan Carbunescu
am 5 Jun. 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
am 5 Jun. 2019
+1
Razvan Carbunescu
am 6 Jun. 2019
For the example you gave above how does the solution look and what does 'similar number' for the first column mean?
Razvan Carbunescu
am 7 Jun. 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
am 1 Jun. 2017
Bearbeitet: Julian Hapke
am 1 Jun. 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 Kommentar
Johannes Korsawe
am 1 Jun. 2017
the second solution exhibits pathological tendencies...
Kategorien
Mehr zu Data Type Identification finden Sie in Hilfe-Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!