Sorting a matrix using it's index

12 ビュー (過去 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 Center および File ExchangeShifting and Sorting Matrices についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by