How can I count the occurrences of each element in a vector in MATLAB?
Show older comments
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].
Accepted Answer
More Answers (3)
Andrei Bobrov
on 14 Aug 2014
[a,b] = histc(x,unique(x));
y = a(b);
1 Comment
Andrei Bobrov
on 3 Aug 2015
y = accumarray(x(:),1)
Razvan Carbunescu
on 9 May 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 Comments
Razvan Carbunescu
on 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
on 5 Jun 2019
+1
Razvan Carbunescu
on 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
on 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
on 1 Jun 2017
Edited: Julian Hapke
on 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 Comment
Johannes Korsawe
on 1 Jun 2017
the second solution exhibits pathological tendencies...
Categories
Find more on Data Type Identification 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!