3

Let's say I have an array arr of doubles:

arr = 120,121,118,119,117,123,120

And a value x

x = 120

I want to get this value

newarr = 120,120,119,121,118,117,123

Which is a new array, the same size of arr, but the values are sorted in relation to the value x, having the closest value first (doesn't matter if it's ascending or descending).

Any idea?

1 Answer 1

6

One approach -

[~,idx] = sort(abs(x-arr))
out = arr(idx)

Output -

out =
   120   120   121   119   118   117   123

Since, 191 & 121 are equidistant from x = 120, the output values appear to be different than the ones listed in the expected output of the problem. In this approach, when two such equidistant values appear in arr, the ones appearing at the start are put at the start in the output array too, thus the order of elements is maintained or it's stable in the output array. As, an example to demonstrate this "stability", here's a sample run with modified arr and keeping x the same at 120 -

>> arr
arr =
   120   121   118   119   117   123   121   119
>> out
out =
   120   121   119   121   119   118   117   123

Note: If you would like to have an ascending order for the equidistant elements, you can first sort arr and then use this approach.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.