简体   繁体   English

在数组中查找不等于给定点的最近点

[英]Finding nearest point in an array that is not equal to given point

I have a point and an array of values.我有一个点和一组值。 I wish to find the closest point y in the array such that x.= y, Currently I am using the standard Scipy KDTree approach in Python. but this does not consider only unique points?我希望在数组中找到最近的点 y,使得 x.= y,目前我在 Python 中使用标准的 Scipy KDTree 方法。但这不只考虑唯一点吗? Is there any workaround to this or does it require a manual implementation?是否有任何解决方法或是否需要手动实施? Thanks!谢谢!

2D ARRAY SOLUTION : I recycled most of the same method as before but this time it ought to work for your structure 2D ARRAY SOLUTION :我回收了大部分与以前相同的方法,但这次它应该适用于您的结构

import math

X = [0,0] # Your cooridinate
x1 = X[0]
y1= X[1]

array = [[1,1],[0,1],[1,0],[-2,2]] # Sample array of data
smallestDistance = 9999 # Make it big so it can be replaced immediately, essentially just a placeholder

for point in array:
    x2 = point[0]
    y2 = point[1]
    separation = math.hypot(x2 - x1, y2 - y1) #Distance equation in easy format
    if separation < smallestDistance and separation!=0:  # Could make this <= instead of < if you want to replace any ties for closest point
        smallestDistance = separation
        closestPoint = point
print(f"Nearest cooridinate = {closestPoint}, separation from {X} is: {smallestDistance}")

OLD SOLUTION FOR 1D ARRAY : I'm not too sure what the structure of your array is, but from what I can tell you've got a 1d array and a given value within in;一维数组的旧解决方案:我不太确定你的数组结构是什么,但据我所知你有一个一维数组和一个给定的值; you want the closest unique value in the array to the original one in question.您希望数组中最接近原始值的唯一值。 If this is correct, the quick and dirty solution could be something akin to:如果这是正确的,那么快速而肮脏的解决方案可能类似于:

smallestDifference = 99999999 #Make this some large number
y = array[someindex]
for thing in array:
     difference = abs(thing-y)
          if difference<smallestDifference & difference != 0:  #Must be closer than the last recorded closest point, AND non-zero i.e. a unique point
               smallestDifference = difference #New smallest distance between points
               closestPoint = thing #Record the new closest point
print(f"x = {closestPoint}, |y-x| = {smallestDifference}")

Might be a bit trickier if this a >1d array and probably not the fastest solution since it has to check every point.. but probably would get the job done:-)如果这是一个 >1d 数组并且可能不是最快的解决方案,可能会有点棘手,因为它必须检查每个点..但可能会完成工作:-)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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