Find the index of the closest value to a given value in a numpy array. Limited to external indices

I have an array called like this:

[[ 315.    326.31  341.57    0.     18.43   33.69   45.  ]
[ 303.69  315.    333.43    0.     26.57   45.     56.31]
[ 288.43  296.57  315.      0.     45.     63.43   71.57]
[ 270.    270.    270.      0.     90.     90.     90.  ]
[ 251.57  243.43  225.    180.    135.    116.57  108.43]
[ 236.31  225.    206.57  180.    153.43  135.    123.69]
[ 225.    213.69  198.43  180.    161.57  146.31  135.  ]]

      

I want to find an array and find the index of the closest value from a given value (e.g. 45). This is what I have been doing so far:

x = np.abs(directions-45)
idx = np.where(x == x.min())

      

This works because it returns all indexes that meet these criteria. However, I want to restrict the returned indices to only those on the outer edge of the array, that is, on the top and bottom rows, and the far right and left columns. If the number is closer to a given value that is not in the outer edges, then I would like to expand the search until the closest number is found on the outer edges.

Thank!

+3


source to share


1 answer


You can add the line

x[1:-1, 1:-1] = x.max()+1

      



before you find idx

to overwrite the center values ​​with a value greater than any edge value.

x = np.abs(directions-45)
x[1:-1, 1:-1] = x.max()+1
idx = np.where(x == x.min())
idx
Out[25]: (array([0], dtype=int64), array([6], dtype=int64))

      

0


source







All Articles