[英]Fastest way to find the closest point to a given point in 3D, in Python
因此,可以說我在A中有10,000點,在B中有10,000點,並且想找出每個B點中A中最接近的點。
目前,我只是遍歷B和A中的每個點,以找出距離最近的那個點。 即。
B = [(.5, 1, 1), (1, .1, 1), (1, 1, .2)]
A = [(1, 1, .3), (1, 0, 1), (.4, 1, 1)]
C = {}
for bp in B:
closestDist = -1
for ap in A:
dist = sum(((bp[0]-ap[0])**2, (bp[1]-ap[1])**2, (bp[2]-ap[2])**2))
if(closestDist > dist or closestDist == -1):
C[bp] = ap
closestDist = dist
print C
但是,我敢肯定有一種更快的方法來執行此操作...有什么想法嗎?
我通常在這種情況下使用kd樹 。
有一個用SWIG包裝並與BioPython捆綁在一起的C ++實現 ,易於使用。
您可以使用numpy廣播。 例如,
from numpy import *
import numpy as np
a=array(A)
b=array(B)
#using looping
for i in b:
print sum((a-i)**2,1).argmin()
將打印2,1,0,分別是A中最接近B的1,2,3行的行。
否則,您可以使用廣播:
z = sum((a[:,:, np.newaxis] - b)**2,1)
z.argmin(1) # gives array([2, 1, 0])
希望對您有所幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.