Sort function indices in regards to the original data?

2 ビュー (過去 30 日間)
Nope
Nope 2024 年 1 月 30 日
編集済み: Matt J 2024 年 1 月 31 日
Using the sort function in descending order results in correctly sorted values, but incorrect indices (in regards to the original data):
[val,idx] = sort([86.9565 69.5652 65.2174 52.1739 43.4783 65.2174 91.3043 60.8696],'descend')
val =
91.3043 86.9565 69.5652 65.2174 65.2174 60.8696 52.1739 43.4783
idx =
7 1 2 3 6 8 4 5
The correct idx should be: 2 3 4 7 8 5 1 6
I should note that I want the idx in regards to the original data, e.g. first element of tre vector is 86.9565, what is the idx of this in the sorted vector. Correct answer would be 2, but Matlab gives the idx in regards to the sorted data.
Is there a way to get the idx in regards to the original data?

採用された回答

the cyclist
the cyclist 2024 年 1 月 31 日
編集済み: the cyclist 2024 年 1 月 31 日
In response to your comment on my other answer (which I posted before you edited your question), here is how to get what you want:
[val,idx] = sort([86.9565 69.5652 65.2174 52.1739 43.4783 65.2174 91.3043 60.8696],'descend');
[~,idx2] = sort(idx)
idx2 = 1×8
2 3 4 7 8 5 1 6
  2 件のコメント
Nope
Nope 2024 年 1 月 31 日
Perfect, thank you!
Matt J
Matt J 2024 年 1 月 31 日
編集済み: Matt J 2024 年 1 月 31 日
You don't need the overhead of a second sort operation to get the desired idx2. See below.

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

その他の回答 (2 件)

Matt J
Matt J 2024 年 1 月 31 日
編集済み: Matt J 2024 年 1 月 31 日
[val,is] = sort([86.9565 69.5652 65.2174 52.1739 43.4783 65.2174 91.3043 60.8696],'descend');
idx=1:numel(val);
idx(is)=idx;
val,
val = 1×8
91.3043 86.9565 69.5652 65.2174 65.2174 60.8696 52.1739 43.4783
idx,
idx = 1×8
2 3 4 7 8 5 1 6

the cyclist
the cyclist 2024 年 1 月 31 日
I'm not sure why you think it should be [2 3 4 7 8 5 1 6].
But, the output is correct.
  • The 7th element is the largest
  • The 1st element is next largest
  • ...
  • The 5th element is the smallest
  1 件のコメント
Nope
Nope 2024 年 1 月 31 日
Sorry, the original question needed editing.

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

カテゴリ

Help Center および File ExchangeShifting and Sorting Matrices についてさらに検索

タグ

製品


リリース

R2023b

Community Treasure Hunt

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

Start Hunting!

Translated by