Sorting a matrix using it's index

1 view (last 30 days)
Alexander Coles
Alexander Coles on 30 Jul 2020
Edited: Bruno Luong on 30 Jul 2020
Hello Matlab users,
My problem is a simple one. But I've had no luck finding a solution on the forums, possibly due to not being able to describe my problem sufficiently.
I want to use the sort function, on matrix A:
A = [2,5,4,1,6;
9,8,3,7,0]
If I use the following function to sort A by rows:
[Asort,idA] = sort(A,2)
I get the expected result:
Asort = [1,2,4,5,6;
0,3,7,8,9]
and the corresponding index matrix:
idA = [4,1,3,2,5;
5,3,4,2,1]
Next, I wish to use this index on another matrix B. But first, I can check by using it again on A:
Asort2 = A(idA)
This method doesn't work as it's now indexing using the entire matrix and not on a row-by-row basis. To get around this, I have had to implement the following for loop to work on each row:
for ii = 1:size(A,1)
Asort2(ii,:) = A(ii,idA(ii,:));
end
This is not the most elegant solution. Is there a preferred/more concise way of doing this operation?
Thanks for your help!

Answers (2)

madhan ravi
madhan ravi on 30 Jul 2020
Edited: madhan ravi on 30 Jul 2020
Asort2 = A(sub2ind(size(A), repmat((1:size(A,1)).', 1, size(A,2)), idA))

Bruno Luong
Bruno Luong on 30 Jul 2020
Edited: Bruno Luong on 30 Jul 2020
[Asort,idA] = sort(A,2)
m = size(A,1);
ilinA = (idA-1)*m+(1:m)';
Asort3 = A(ilinA) % get back Asort

Categories

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

Community Treasure Hunt

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

Start Hunting!