Sorting a matrix using it's index

1 visualización (últimos 30 días)
Alexander Coles
Alexander Coles el 30 de Jul. de 2020
Editada: Bruno Luong el 30 de Jul. de 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!

Respuestas (2)

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

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

Categorías

Más información sobre Matrix Indexing en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by