简体   繁体   中英

Finding the distance of the 5th closest point to each of the points in a list of points

 xy[0].sort()
 DT=[]
 for i in range(5982):
       xf=np.abs(xy[0][i]-xy[0][i+1])
       yf=np.abs(xy[1][i]-xy[1][i+1])
       D=((xf**2)+(yf**2))**0.5
       DT.append(D)`

 DT.sort()
 R5=[]
 for i in range(5977):
    R=np.abs(DT[i]-DT[i+4])
    R5.append(R)`

As the title suggests I'm trying to find the 5th closest point to each of the points in the list xy which consists of all the points in the shape (2,5983), however the method Im using returns the 5th closest distance without taking into account points in both the x and y direction. Any help on resolving this would be greatly appreciated!

Use:

from scipy.spatial.distance import pdist,squareform
Y = pdist(xy, 'euclidean')

Example:

>>a = [[1,2],[3,4],[5,6]]
>>Y = pdist(a, 'euclidean')
>>Y
array([2.82842712, 5.65685425, 2.82842712])

The first element is the distance between a0 and a1, the second is distance between a0 and a2 and the third is distance between a1 and a2.

Or you can use the square form:

>>square = squareform(pdist(a))
>>square
array([[0.        , 2.82842712, 5.65685425],
       [2.82842712, 0.        , 2.82842712],
       [5.65685425, 2.82842712, 0.        ]])

After that, use:

np.argsort(square)

And you will get what you want.

Check the pdist documentation .

If I understand correctly what you want, this should give you the index of the 5th closest:

fifth = []
for i in range(len(xy)):
    distances = ((xy.T-xy.T[i])**2).sum(axis=1)
    fifth.append(np.argsort(distances)[5])

This works if xy is in the shape (samples,dimensions) so I am using transport. Otherwise it makes the iterations less readable imo. But you could change this. You calculate all the distances at ones, there is no need to do sqrt because sqrt is monotonous, and you are looking for order only. Then I use the 6th element (index 5) because for simplicity, I am not skipping the self, which will be distance 0. Hope this helps and is clear

Trying not to change your code too much. The first part computes the square of the distance between each pair of points (as pointed by Tacratis the square root is monotonous). Then it finds the fifth closest point to each point and returns an array where the i th element is the fifth closest point the the point i .

DT = []
    for i in range(5983):
        d_i = []
        for j in range(5983):
            xf=np.abs(xy[0][i]-xy[0][j])
            yf=np.abs(xy[1][i]-xy[1][j])
            d_ij =(xf**2)+(yf**2)
            d_i.append(d_ij)
        DT.append(d_i)

R5 = []
for i in range(5983):
    R = DT[i].index(sorted(DT[i])[5]) 
    R5.append(R)

print R5 

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