[SciPy-User] Finding closest point in array - inverse of KDTree

Daπid davidmenhur at gmail.com
Wed Oct 11 16:13:06 EDT 2017

On 11 October 2017 at 19:01, Antonio Polino <antoniy.py at gmail.com> wrote:

> On the other hand, the array A is always the same, only k changes. So it
> would be beneficial to use some auxiliary structure (like a "inverse
> KDTree") on A, and then query the results on the small array k.

You can sort A and use searchsorted to find the positions of the midpoints
of k. Then, you assign the values to the group.

In your example (adding one more and sorting k):

    >>> A = np.asarray([3, 4, 5, 6])
    >>> k = np.asarray([3, 4.1, 5.2])
    >>> midpoints = np.array([ 3.55,  4.65])   #  k[:-1] + np.diff(k) / 2
    >>> np.searchsorted(A, midpoints)
    array([1, 2])

So, this means that A[:1] belong to k[0], A[1:2] belong to k[2] and A[2:]
belong to k[3]


PS: in your later email I see your name as Ant.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/scipy-user/attachments/20171011/32fde2dc/attachment.html>

More information about the SciPy-User mailing list