sorting an array in a specific order

2 vues (au cours des 30 derniers jours)
Max
Max le 10 Août 2022
Commenté : Max le 10 Août 2022
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]?

Réponse acceptée

Matt J
Matt J le 10 Août 2022
Modifié(e) : Matt J le 10 Août 2022
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 commentaire
Max
Max le 10 Août 2022
Thank you so much!

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Shifting and Sorting Matrices dans Help Center et File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by