To arrange matrix based off criteria in column

조회 수: 1 (최근 30일)
Cside
Cside 2019년 12월 4일
댓글: Star Strider 2019년 12월 4일
Hi i have a 60x2 matrix, with the first column being a number from 1 to 300 (not consecutive), and the second column with locations from 1 to 9. I have attached a picture to show how it looks like and would like to regroup into a new matrix (AB) of 9x____, the rows being the locations (1:9), and the columns being the numbers that have the respective locations i.e. in the first column, if numbers 8, 16 & 52 have a corresponding location 1 in column 2, AB row 1 will be 8,16,52 (1 in each column, total 3 columns). What functions should I use for this/any ideas how to write for this?
Thank you! :)
ferfw.JPG

채택된 답변

Star Strider
Star Strider 2019년 12월 4일
Try this:
Col1 = randperm(300); % Create Column 1
Col2 = randi(9, 1, 300); % Create Column 2
M = [Col1(:) Col2(:)]; % Create Matrix
Gather = accumarray(M(:,2), M(:,1), [], @(x){x.'}); % Cell Array With Desired Information
AB = {(1:9).', Gather};
That should work. You will need to keep ‘AB’ as a cell array because there are different numbers of columns in each row. You might be able to use a structure to store this information, however I doubt that a table would work correctly.
Experiment to get the result you want.
  댓글 수: 2
Cside
Cside 2019년 12월 4일
Thanks star strider! Played around with it and got it :)
Star Strider
Star Strider 2019년 12월 4일
As always, my pleasure!
To get the individual rows of ‘AB’:
Row1 = [AB{1}(1) AB{2}{1}]
Row2 = [AB{1}(2) AB{2}{2}]
and so for the rest.

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Matrix Indexing에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by