How do I extract data from a matrix with a specific column value and place into a row in a new matrix.
조회 수: 4 (최근 30일)
이전 댓글 표시
Lets say I have a 2 x 10 matrix M
The first column being an ID, and the second a value
1, 25
3, 33
3. 45
2, 22
4, 54
4, 56
5, 23
5, 65
1, 27
2, 29
How could I sort this matrix into a matrix such that each row represents a value, and the columns are each value that is mapped to the same ID such that the new matrix would be.
1, 25, 27
2, 22, 29
3, 33, 45
4, 54, 56
5, 23, 65
댓글 수: 1
the cyclist
2023년 5월 21일
Is it guaranteed that the first column will have equal numbers of duplicated rows, for each unique value?
If not, how do you want to handle it?
[Minor bit of info: In MATLAB, that is referred to as a 10x2 matrix.]
답변 (1개)
the cyclist
2023년 5월 21일
Here is a straightforward method, assuming equal number of duplicates in the first column.
% Input
M = [1, 25
3, 33
3. 45
2, 22
4, 54
4, 56
5, 23
5, 65
1, 27
2, 29];
% Find the unique values in the first column (and the index from these unique value back to M)
[uniqueM,~,indexFromUniqueBackToM] = unique(M(:,1));
% Number of rows and columns in the output array
nrow = numel(uniqueM);
ncol = height(M)/nrow + 1;
% Initialize the output
output = zeros(nrow,ncol);
% Loop over the unique values, and fill in the corresponding rows
for nr = 1:nrow
output(nr,1) = uniqueM(nr);
output(nr,2:end) = M(indexFromUniqueBackToM==nr,2)';
end
output
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Logical에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!