keeping track of the original indices of an array after sorting

56 ビュー (過去 30 日間)
Md Tanvir Rahman
Md Tanvir Rahman 2015 年 6 月 25 日
回答済み: Leelakrishna Vuriti 2019 年 12 月 3 日
I have an array let's say A=[5 4 1 2 3]. Now I have sorted these arrays in ascending order.So the resulting array will now be [1 2 3 4 5]. I use sort(A,'ascend') function to sort this. The question is how can I get the indices of the original array with respect to my new array. originally my indices were 1,2,3,4,5 for corresponding values of 5,4,1,2,3 and now the indices have changed to 3,4,5,2,1. How can I get these indices efficiently in Matlab?
  1 件のコメント
Stephen23
Stephen23 2015 年 6 月 25 日
編集済み: Stephen23 2015 年 6 月 25 日
The documentation clearly explains that the function sort has two outputs... the second output are the indices that you are after.

サインインしてコメントする。

採用された回答

Mischa Kim
Mischa Kim 2015 年 6 月 25 日
Md, simply use
[B,I] = sort(A,'ascend')
B =
1 2 3 4 5
I =
3 4 5 2 1

その他の回答 (2 件)

Andy
Andy 2017 年 4 月 3 日
and B = A(I), according to documentation, isn't it?
I get following:
>> x = [ 1 3 2 7; 4 3 2 1]
x =
1 3 2 7
4 3 2 1
>> [y,i] = sort(x,2)
y =
1 2 3 7
1 2 3 4
i =
1 3 2 4
4 3 2 1
>> y1 = x(i)
y1 =
1 3 4 3
3 3 4 1
I see y1 is different from y ...
  2 件のコメント
Stephen23
Stephen23 2017 年 4 月 3 日
編集済み: Stephen23 2018 年 3 月 21 日
"and B = A(I), according to documentation, isn't it?"
The documentation states "if A is a vector, then B = A(I)." Is your input a vector? NO. However you can esaily read the rest of the documentation, where it explains the output for matrices and arrays: "The index vectors are oriented along the same dimension that sort operates on. For example, if A is a 2-by-3 matrix, then [B,I] = sort(A,2) sorts the elements in each row of A. The output I is a collection of 1-by-3 row index vectors describing the rearrangement of each row of A."
And your data shows this clearly:
i =
1 3 2 4
4 3 2 1
Have a look: do you see that these are the indices along each row, which is exactly what the documentation states that you would get. It means you cannot use A(I) syntax. You could use sub2ind though.

サインインしてコメントする。


Leelakrishna Vuriti
Leelakrishna Vuriti 2019 年 12 月 3 日
Capture2.JPG
how to arrange the values in ascending order along with its corresponding index change ? what is the command for this ? help me out !

カテゴリ

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