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

11 Ansichten (letzte 30 Tage)
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 Kommentar
the cyclist
the cyclist am 21 Mai 2023
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.]

Melden Sie sich an, um zu kommentieren.

Antworten (1)

the cyclist
the cyclist am 21 Mai 2023
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

Kategorien

Mehr zu Creating and Concatenating Matrices finden Sie in Help Center und File Exchange

Produkte


Version

R2022b

Community Treasure Hunt

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

Start Hunting!

Translated by