How to get all values existing in arrays/matrices?

81 visualizaciones (últimos 30 días)
Arif Widianto
Arif Widianto el 24 de Mzo. de 2020
Editada: Andrei Bobrov el 24 de Mzo. de 2020
Hello,
Let say I have a 3-by-2 array with random integer values. For example,
myArray = [98 56; 58 52; 100 56];
What I want to do is, I want to get all value in the array and its frequency and save it to another array like this,
listValue = [98 1; 56 2; 58 1; 52 1; 100 1];
Is there any function or a way to do it?
Thank you in advance.

Respuesta aceptada

Andrei Bobrov
Andrei Bobrov el 24 de Mzo. de 2020
Editada: Andrei Bobrov el 24 de Mzo. de 2020
[a,~,c] = unique(reshape(myArray',[],1),'stable');
out = [a, accumarray(c,1)];
or
out = varfun(@(x)x,array2table(myArray(:)),'GroupingVariables',1);
  2 comentarios
Arif Widianto
Arif Widianto el 24 de Mzo. de 2020
Editada: Arif Widianto el 24 de Mzo. de 2020
The first one works for my case. So, if I want it sorted, the only thing I need to do is changing 'stable' to 'sorted' right?
Andrei Bobrov
Andrei Bobrov el 24 de Mzo. de 2020
Editada: Andrei Bobrov el 24 de Mzo. de 2020
Yes or:
[a,~,c] = unique(myArray);
out = [a, accumarray(c,1)];

Iniciar sesión para comentar.

Más respuestas (2)

KSSV
KSSV el 24 de Mzo. de 2020
Editada: KSSV el 24 de Mzo. de 2020
Read about unique
a = myArray(:) ;
[cnt_unique, unique_a] = hist(a,unique(a)) ;

Walter Roberson
Walter Roberson el 24 de Mzo. de 2020
See unique() and accumarray. Or unique and histc or histcounts (but be careful about the last value in histcounts). Or use a loop. Or use sparse(). Lots of ways.

Categorías

Más información sobre Creating and Concatenating Matrices en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by