sorting an array in a specific order

How would I sort array elements in ascending order based on how close they are to a specific value. For example if x=[1 2 2.5 3 4 5] and y= 3.4 how would I make x arrange as [3 4 2.5 2 5 1]?

 採用された回答

Matt J
Matt J 2022 年 8 月 10 日
編集済み: Matt J 2022 年 8 月 10 日

0 投票

x=[1 2 2.5 3 4 5]; y= 3.4;
[~,is]=sort(abs(x-y))
is = 1×6
4 5 3 2 6 1
x=x(is)
x = 1×6
3.0000 4.0000 2.5000 2.0000 5.0000 1.0000

1 件のコメント

Max
Max 2022 年 8 月 10 日
Thank you so much!

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

その他の回答 (0 件)

カテゴリ

ヘルプ センター および File ExchangeShifting and Sorting Matrices についてさらに検索

タグ

質問済み:

Max
2022 年 8 月 10 日

コメント済み:

Max
2022 年 8 月 10 日

Community Treasure Hunt

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

Start Hunting!

Translated by