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

1 view (last 30 days)
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]

Accepted Answer

MathWorks Support Team
MathWorks Support Team on 15 Jun 2018
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

More Answers (0)

Categories

Find more on Shifting and Sorting Matrices in Help Center and File Exchange

Products


Release

R2018a

Community Treasure Hunt

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

Start Hunting!