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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With