Count the number of same elements in an array

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..

 Respuesta aceptada

madhan ravi
madhan ravi el 10 de Sept. de 2019
Editada: madhan ravi el 10 de Sept. de 2019
[~,~,ix] = unique(V);
C = accumarray(ix,1).'

5 comentarios

luca
luca el 10 de Sept. de 2019
may you explain your answer?
there's a precision that I have to put.
If there is no 1 element like
V = [2 2 3 4 5 6 7 7 8 8 9 9]
I would like to obtain
C= [0 2 1 1 1 1 2 2 2]
Where the entities 1 is not present so the first element is 0.
Do you know how to do it?
madhan ravi
madhan ravi el 10 de Sept. de 2019
Editada: madhan ravi el 10 de Sept. de 2019
C=accumarray(V(:),1).'
%or
C=sum(V(:)==(1:max(V)))
As per your latter comment Stephen’s approach below will do what you want.
Stephen23
Stephen23 el 10 de Sept. de 2019
Editada: Stephen23 el 10 de Sept. de 2019
@madhan ravi : this is really quite neat:
accumarray(V(:),1)
Simple idea which works well:
>> V = [2 2 3 4 5 6 7 7 8 8 9 9]
>> accumarray(V(:),1)
ans =
0
2
1
1
1
1
2
2
2
madhan ravi
madhan ravi el 10 de Sept. de 2019
Thank you Stephen :) !

Iniciar sesión para comentar.

Más respuestas (3)

Stephen23
Stephen23 el 10 de Sept. de 2019
Editada: Stephen23 el 10 de Sept. de 2019
Your 1st example:
>> 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];
>> C = hist(V,1:max(V))
C =
2 4 6 5 6 3 3 4 1
Your 2nd example:
>> V = [2 2 3 4 5 6 7 7 8 8 9 9]
>> C = hist(V,1:max(V))
C =
0 2 1 1 1 1 2 2 2
Vitek Stepien
Vitek Stepien el 14 de Ag. de 2021
Editada: Vitek Stepien el 14 de Ag. de 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'
ans = 1×9
1 2 3 4 5 6 7 8 9
gc'
ans = 1×9
2 4 6 5 6 3 3 4 1
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.
Hugo Diaz
Hugo Diaz el 28 de Nov. de 2020

0 votos

I use sparse(V(:),V(:), 1) for large arrays with missing indices.

Productos

Versión

R2019a

Preguntada:

el 10 de Sept. de 2019

Editada:

el 14 de Ag. de 2021

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by