I used to use min([a, b], key=lambda x:abs(x-x0)) to find which of a and b are the closest to x0.
a = 1
b = 2
x0 = 1.49
print(min([a, b], key=lambda x:abs(x-x0)))
# >>> 1
Now, a and b are numpy arrays with an arbitrary number of dimensions. I would like to build an array composed of the closest values to x0 between both arrays, element by element.
import numpy as np
a = np.array([[1, 2], [3, 5]])
b = np.array([[6, 2], [6, 2]])
## case 1
x0 = 4
# >>> should return np.array([[6, 2], [3, 5]])
## case 2
x0 = np.array([[1, 2], [3, 4]])
# >>> should return np.array([[1, 2], [3, 5]])
To find the elementwise minimum between two arrays, we can use numpy.minimum.
Unfortunately, it does not take lambda functions as arguments.
How should I do ?
arbitrary number of dimensionsis somewhat arbitrary. Are their dimensions equal, and how do they relate to the dimension ofx0? Do you have a sample in hand?x0is a single float. The dimensions ofaandbshould not play in this problem, as soon asa.shape == b.shape, right ?