How do I sort the rows of a matrix by a certain column, given the ordering specified in a separate vector?

1 次查看(过去 30 天)
How do I sort the rows of a matrix by a certain column, given the ordering specified in a separate vector and without a for loop?
For example we have A and B:
A =[ 3 1 5]
B =[ 5 55
3 33
1 11
3 333
5 555
1 111]
and wish to reshape B by the first column using the order specified in A to give C:
C =[3 33
3 333
1 11
1 111
5 55
5 555]

采纳的回答

MathWorks Support Team
There are likely many ways to do this without a for loop. One way is to cast the first column of matrix to a Categorical data type. We can think of the first column as a discrete set of categories rather than a numeric datatype. Then by specifying these categories as ordinals, we can rank them, and use this information to sort. See the below steps to do this using the example:
% The example data:
A=[3 1 5]; %the indexing vector
B=[5 55;3 33;1 11;3 333;5 555;1 111]; %the matrix to be sorted
% Step 1 convert the first row of B to a categorical datatype and save to a
% temporary variable.
B_Cat = categorical(B(:,1),A,'Ordinal',true);
% Note: We use A to define the category names. By also
% specifying it as an Ordinal, the order of categories specified in A
% determines the ranking used when sorting or comparing.
% Step 2: sort the temporary variable, save the indices for rearranging B.
[~,I] = sort(B_Cat);
% Step 3: Rearrange B by using the indices from the previous step to create
% the desired C matrix
C = B(I,:)
The output is:
C =
3 33
3 333
1 11
1 111
5 55
5 555

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Shifting and Sorting Matrices 的更多信息

产品


版本

R2018a

Community Treasure Hunt

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

Start Hunting!

Translated by