Azzera filtri
Azzera filtri

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

4 visualizzazioni (ultimi 30 giorni)
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.

Risposta accettata

Stephen23
Stephen23 il 10 Feb 2016
Modificato: Stephen23 il 10 Feb 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 Commento
Amine Ben Ayara
Amine Ben Ayara il 10 Feb 2016
THANK YOU IS NOT enough to show my gratitude for your help! LIFE SAVER again!!!!!!! I REALLY appreciate it

Accedi per commentare.

Più risposte (1)

Guillaume
Guillaume il 10 Feb 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))]

Categorie

Scopri di più su Matrices and Arrays in Help Center e File Exchange

Tag

Community Treasure Hunt

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

Start Hunting!

Translated by