How to group by matrix by row numbers
3 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
Assume matrix A as follows:
A = [
12 4 5 4 3 4 2
12 3 1 6 1 8 10
12 5 10 3 9 1 9
14 6 5 4 5 6 5
14 8 4 7 3 7 10
16 1 5 3 6 3 6
16 6 4 9 8 5 6
98 4 10 1 5 7 9
98 8 8 4 6 1 9
98 5 3 6 10 3 3
98 3 2 6 5 5 9
];
I want to group by matrix A based on the unique ID (first column) and row numbers. For example, looking at first column of matrix A, there are four unique IDs (12,14,16,98). So, for output matrix A1, I want every first row from these unique ID to add in matrix A1. For output A2, the second row, and so on.
0 commentaires
Réponses (1)
Stephen23
le 11 Mai 2017
Modifié(e) : Stephen23
le 11 Mai 2017
One way to split into those groups, although it does not preserve the row order, is to use accumarray:
>> [~,~,idx] = unique(A(:,1));
>> C = accumarray(idx,ones(size(idx)),[],@(v){cumsum(v)});
>> D = accumarray(vertcat(C{:}),(1:size(A,1)).',[],@(r){A(r,:)});
>> D = cellfun(@sortrows,D,'uni',0);
>> D{:}
ans =
12 4 5 4 3 4 2
14 6 5 4 5 6 5
16 1 5 3 6 3 6
98 4 10 1 5 7 9
ans =
12 3 1 6 1 8 10
14 8 4 7 3 7 10
16 6 4 9 8 5 6
98 8 8 4 6 1 9
ans =
12 5 10 3 9 1 9
98 5 3 6 10 3 3
ans =
98 3 2 6 5 5 9
0 commentaires
Voir également
Catégories
En savoir plus sur Matrices and Arrays dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!