Effacer les filtres
Effacer les filtres

How Do I find unique values of an element in a matrix

4 vues (au cours des 30 derniers jours)
Amine Ben Ayara
Amine Ben Ayara le 10 Fév 2016
Commenté : Amine Ben Ayara le 10 Fév 2016
I have a matrix that is (110500*4); the First column are identiers/IDs, these values are not unique, meaning same value can appear more than once. I need to find out how many times each ID appears then basically aggregate the matrix based on these unique IDs to where 1st column is: Unique IDs, 2nd, 3rd and 4th : Sum of elements from original table associated with unique ID. Example:
A=[5 12 25 0
2 10 24 0
1 7 25 1
5 5 12 0
2 6 23 1];
then end matrix should have only 3 rows (unique values are 5,2 & 1) with 1st column: unique values, 2nd column : Sum of values associated with unique ID (5) from column 2, and same for the next 2 columns. basically, reduce the matrix to unique ID then aggregate the next columns based on that.

Réponse acceptée

Stephen23
Stephen23 le 10 Fév 2016
Modifié(e) : Stephen23 le 10 Fév 2016
>> A = [5,12,25,0;2,10,24,0;1,7,25,1;5,5,12,0;2,6,23,1]
A =
5 12 25 0
2 10 24 0
1 7 25 1
5 5 12 0
2 6 23 1
>> [val,~,idx] = unique(A(:,1));
>> out(:,4) = accumarray(idx,A(:,4));
>> out(:,3) = accumarray(idx,A(:,3));
>> out(:,2) = accumarray(idx,A(:,2));
>> out(:,1) = val
out =
1 7 25 1
2 16 47 1
5 17 37 0
  1 commentaire
Amine Ben Ayara
Amine Ben Ayara le 10 Fév 2016
THANK YOU IS NOT enough to show my gratitude for your help! LIFE SAVER again!!!!!!! I REALLY appreciate it

Connectez-vous pour commenter.

Plus de réponses (1)

Guillaume
Guillaume le 10 Fév 2016
unique together with accumarray will do exactly what you want:
A=[5 12 25 0; 2 10 24 0; 1 7 25 1; 5 5 12 0; 2 6 23 1];
[values, ~, subs] = unique(A(:, 1));
out = [values, ...
accumarray(subs, A(:, 2)), ...
accumarray(subs, A(:, 3)), ...
accumarray(subs, A(:, 4))]
Another way of doing the last line, with just one call to accumarray:
out = [values, accumarray([repelem(subs, 3), repmat((1:3)', numel(subs), 1)], reshape(A(:, 2:4), [], 1))]

Catégories

En savoir plus sur Matrices and Arrays dans Help Center et File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by