How to group by matrix by row numbers
조회 수: 4 (최근 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.
댓글 수: 0
답변 (1개)
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
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Matrices and Arrays에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!