I\'m beginning to learn Python coming from a C++ background. What I am looking for is a quick and easy way to find the closest (nearest neighbor) of some multidimensional query
If concise is your goal, you can do this one-liner:
In [14]: X = scipy.randn(10,2)
In [15]: X
Out[15]:
array([[ 0.85831163, 1.45039761],
[ 0.91590236, -0.64937523],
[-1.19610431, -1.07731673],
[-0.48454195, 1.64276509],
[ 0.90944798, -0.42998205],
[-1.17765553, 0.20858178],
[-0.29433563, -0.8737285 ],
[ 0.5115424 , -0.50863231],
[-0.73882547, -0.52016481],
[-0.14366935, -0.96248649]])
In [16]: q = scipy.array([0.91, -0.43])
In [17]: scipy.argmin([scipy.inner(q-x,q-x) for x in X])
Out[17]: 4
If you have several query points:
In [18]: Q = scipy.array([[0.91, -0.43], [-0.14, -0.96]])
In [19]: [scipy.argmin([scipy.inner(q-x,q-x) for x in X]) for q in Q]
Out[19]: [4, 9]