简体   繁体   中英

Finding nearest points in numpy arrays of x and y coordinates

I have two arrays:

a=np.array([[ 41.0,  0.71],
       [ 41.21,  0.87],
       [ 41.14,  0.96],
       [41.5,  0.86])

b=np.array([[ 41.41, 1.51],
       [ 41.3,  0.95],
       [ 41.0,  0.96],
       [42.1,  0.76]),
       [ 40.3,  0.85],
       [ 41.1,  0.76],
       [40.9,  0.96])...]

And for each point in a, I need to find the nearest points in b which are closest to that point within a ratio r.

I already try to do something similar to the example: " Finding index of nearest point in numpy arrays of x and y coordinates " but with no exit, somebody can show me an easy way to use spatial.KDTree or spatial.cKDTree?

Finding the distance can be done like this:

In [1]: import numpy as np

In [2]: a=np.array([[ 41.0,  0.71], [ 41.21,  0.87], [ 41.14,  0.96], [41.5,  0.86]])

In [3]: b=np.array([[ 41.41, 1.51], [ 41.3,  0.95], [ 41.0,  0.96],[42.1,  0.76], [ 40.3,  0.85], [ 41.1,  0.76],[40.9,  0.96]])

Calculate the difference in x and y between a[0] and all points in b (4), then square that (5).

In [4]: c = b - a[0]

In [5]: c*c
Out[5]: 
array([[ 0.1681,  0.64  ],
       [ 0.09  ,  0.0576],
       [ 0.    ,  0.0625],
       [ 1.21  ,  0.0025],
       [ 0.49  ,  0.0196],
       [ 0.01  ,  0.0025],
       [ 0.01  ,  0.0625]])

Sum the square of c over the inner arrays to get the distance squared, then calculate the square root.

In [6]: np.sqrt(np.sum(c*c, axis=1))
Out[6]: 
array([ 0.89894382,  0.38418745,  0.25      ,  1.10113578,  0.71386273,
        0.1118034 ,  0.26925824])

This is the distance from a[0] to every point in b .

Finding the minimum:

In [8]: np.min(np.sqrt(np.sum(c*c, axis=1)))
Out[8]: 0.1118

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM