How do I extract data from a matrix with a specific column value and place into a row in a new matrix.

9 次查看(过去 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
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
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
output = 5×3
1 25 27 2 22 29 3 33 45 4 54 56 5 23 65

类别

Help CenterFile Exchange 中查找有关 Creating and Concatenating Matrices 的更多信息

产品


版本

R2022b

Community Treasure Hunt

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

Start Hunting!

Translated by