How to group by matrix by row numbers

3 次查看(过去 30 天)
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.

回答(1 个)

Stephen23
Stephen23 2017-5-11
编辑:Stephen23 2017-5-11
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

类别

Help CenterFile Exchange 中查找有关 Matrices and Arrays 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by