Reversal of a sort
We can sometimes be motivated to reverse things in Boston. And I occasionally get asked how to reverse the sort direction from MATLAB. So instead of sorting A and then having B follow the new order, let's undo a sorting operation, and in a way that multiple vectors could benefit, if necessary.
Contents
Forward Sorting
To sort multiple additional vectors in the same way as an initial one, we can easily take advantage of the sort index.
A = [1 8 3 17 0 4 7]; [sortA, ind] = sort(A); B = [2 5 6 1 9 3 8]; sortBbyA = B(ind); sortB = sort(B);
Here are the indices required to rearrange A into sortA.
ind
ind = 5 1 3 6 7 2 4
And here's a comparison of the original vectors and the ones sorted by the order in A.
[A;B] [sortA;sortBbyA]
ans = 1 8 3 17 0 4 7 2 5 6 1 9 3 8 ans = 0 1 3 4 7 8 17 9 2 6 3 8 5 1
You can see that each number in A still corresponds to the same value from B after each vector has been sorted based on A.
Now let's have a look at the variants of the vector B.
[B;sortB;sortBbyA]
ans = 2 5 6 1 9 3 8 1 2 3 5 6 8 9 9 2 6 3 8 5 1
You can see that sorting B according to A (the 3rd row) is distinct from sorting B directly (second row).
Reverse Sorting
Suppose instead, I want all my vectors to be sorted the same way that the original A is sorted. I can still use the index from sort but in a different way.
unsorted = 1:length(A); newInd(ind) = unsorted
newInd = 2 6 3 7 1 4 5
We are now in a position to undo the original sorting of A and apply the rearrange variants of B the same way. First we'll work with the variant of B based on sorting from A.
newA = sortA(newInd); newBfromA = sortBbyA(newInd); isequal([newA;newBfromA],[A;B])
ans = 1
Now let's compare several variants: B, the regular sorting of B, B sorted by A, and the sorted B rearranged according to the reverse sorting of A
newB = sortB(newInd); [B;sortB;sortBbyA;newB]
ans = 2 5 6 1 9 3 8 1 2 3 5 6 8 9 9 2 6 3 8 5 1 2 8 3 9 1 5 6
Help Me Here
Now I've shown how to use the direct sorting indices of a vector to reverse sort another vector. I can even vaguely recall needing to do this once, but I can no longer remember why. Do you use this construct? Can you tell me some applications? I'd love to hear about them; please post here.
- Category:
- Indexing,
- Less Used Functionality
Comments
To leave a comment, please click here to sign in to your MathWorks Account or create a new one.