How to group by matrix by row numbers

3 ビュー (過去 30 日間)
Alex Rob
Alex Rob 2017 年 5 月 11 日
編集済み: Alex Rob 2017 年 5 月 11 日
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 Center および File ExchangeResizing and Reshaping Matrices についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by