Getting array sorted with respect to matlab value
Let's say I have an array arr of doubles:
arr = 120,121,118,119,117,123,120
And the x value
x = 120
I want to get this value
newarr = 120,120,119,121,118,117,123
Which new array has the same size arr, but the values ββare sorted relative to the x value having the closest value at the beginning (it doesn't matter if it goes up or down).
Any idea?
One approach -
[~,idx] = sort(abs(x-arr))
out = arr(idx)
Output -
out = 120 120 121 119 118 117 123
Since 191
and are 121
equidistant from x = 120
, the outputs look different than those listed in the expected output of the problem. In this approach, when two such equidistant values ββare mapped to arr
, the ones that appear at the beginning are also prepended in the output array, so the order of the elements maintained
or it is stable
in the output array. As an example demonstrating this "stability", here's a sample of the mileage with a modified arr
and keeping x
the same in 120
-
>> arr arr = 120 121 118 119 117 123 121 119 >> out out = 120 121 119 121 119 118 117 123
Note. If you want ascending order for equidistant elements, you can sort first arr
and then use this approach.