Sorting a matrix using it's index

2 次查看(过去 30 天)
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!

回答(2 个)

madhan ravi
madhan ravi 2020-7-30
编辑:madhan ravi 2020-7-30
Asort2 = A(sub2ind(size(A), repmat((1:size(A,1)).', 1, size(A,2)), idA))

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

类别

Help CenterFile Exchange 中查找有关 Matrix Indexing 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by