I have an array of tuples, I need to find the tuple from that array that is the closes to a given tuple(element wise), that is by the absolute value difference between each element of these two tuples. The array of tuples is like:
array_of_tuples = [(0.0, 6.5, 1),
(0.0, 6.5, 4.5),
(0.0, 6.5, 8.0),
(0.0, 13.5, 1),
(0.0, 13.5, 4.5),
(0.0, 13.5, 8.0),
(0.0, 21.0, 1),
(0.0, 21.0, 4.5),
(0.0, 21.0, 8.0),
(7.0, 6.5, 1),
(7.0, 6.5, 4.5),
(13.5, 21.0, 8.0)]
While the query tuple is (13.1, 20.3, 8.4)
However doing: np.argmin(np.abs(array_of_tuples - (13.1, 20.3, 8.4)))
gives 8
, while if I print the result without np.argmin() I clearly see that it is the last element in the array that has the least difference with the given tuple.
You have to consider all coordinates and aggregate them into a single number (per row).
Compute the sum of squares and get the (arg)min of that:
np.argmin(((array_of_tuples - (13.1, 20.3, 8.4))**2).sum(axis=1))
Output: 11
Intermediate before argmin
:
array([416.81, 377.26, 362.21, 272.61, 233.06, 218.01, 226.86, 187.31,
172.26, 282.41, 242.86, 0.81])
As suggested by @MadPhysicist, you can also use numpy.linalg.norm
to compute the norm per row:
np.argmin(np.linalg.norm(array_of_tuples-(13.1, 20.3, 8.4), axis=1))