grouping numbers in matrix

조회 수: 3 (최근 30일)
Cside
Cside 2019년 10월 23일
댓글: Akira Agata 2019년 10월 23일
Hi, I have 2 matrices
A = [ 1, 2, 3, 2, 2, 3, 3, 1, 1]
B = [34, 20, 23, 31, 30, 33, 44, 22, 28]
and would like to group them according to their numbers in A. The answer should be a 3 x 3 matrix (A corresponds to column number).
Thank you! :)

채택된 답변

Akira Agata
Akira Agata 2019년 10월 23일
More generalized solution would be:
C = splitapply(@(x){x'}, B, A);
If each group has the same number of elements, the following can generate 2D matrix.
B2 = cell2mat(C);
  댓글 수: 2
Cside
Cside 2019년 10월 23일
편집: Cside 2019년 10월 23일
Hi Akira,
Could you break down/explain the first code? Am a new matlab learner :) Also for cell2mat, is there another shortcut i can use to group if they do not have the same number of elements? (I still want the 2D matrix)
Akira Agata
Akira Agata 2019년 10월 23일
Hi Charms-san,
Thank you for your response.
Yes, splitapply is somehow "tricky" function. But, at the same time, this is quite useful and powerful function. So I would recommend accessing the following documentation page. I believe the "Example" section will be useful to uderstand how splitapply works!
Regarding the second question, I believe padding with 'NaN' or something will be needed to adjust number of elements for each group and make the 2D matrix, when they do not have the same number of elements.

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Daniel M
Daniel M 2019년 10월 23일
This is not a generalized solution, and assumes that there will always be three entries of each number (1, 2, 3) in A.
[~,sortOrder] = sort(A);
B2 = reshape(B(sortOrder),3,3)';

카테고리

Help CenterFile Exchange에서 Shifting and Sorting Matrices에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by