Sorting a matrix using it's index

조회 수: 1 (최근 30일)
Alexander Coles
Alexander Coles 2020년 7월 30일
편집: Bruno Luong 2020년 7월 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에서 Shifting and Sorting Matrices에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by