【问题标题】:Distance between one point and rest of the points in an array一个点与数组中其余点之间的距离
【发布时间】:2018-02-04 15:33:57
【问题描述】:

我正在编写一些代码来计算一个点与同一数组中其他点之间的实际距离。该数组保存粒子在 3D 空间中的位置。有 N 个粒子,所以阵列的形状是(N,3)。我选择一个粒子并计算这个粒子与其余粒子之间的距离,所有这些都在一个数组中。

这里有人知道怎么做吗?

到目前为止我所拥有的:

xbox = 10
ybox = 10
zbox = 10
nparticles =15
positions = np.empty([nparticles, 3])
for i in range(nparticles):
     xrandomalocation = random.uniform(0, xbox)
     yrandomalocation = random.uniform(0, ybox)
     zrandomalocation = random.uniform(0, zbox)
     positions[i, 0] = xrandomalocation
     positions[i, 1] = yrandomalocation
     positions[i, 2] = zrandomalocation

这就是我现在所拥有的。我正在考虑使用np.linalg.norm,但是我完全不确定如何在我的代码中实现它(或者可能在循环中使用它)?

【问题讨论】:

  • 你能放一些你试过的代码吗?至少数组?
  • this(问题的第一行)有帮助吗?
  • 欢迎来到 StackOverflow!请阅读how to ask a question(尤其是how to create a good example)以获得良好的响应。在您的情况下,发布一个示例数组和预期的输出会很有用。
  • 您似乎希望我们为您编写一些代码。虽然许多用户愿意为陷入困境的程序员编写代码,但他们通常只在发布者已经尝试自己解决问题时才提供帮助。展示这项工作的一个好方法是包含您迄今为止编写的代码、示例输入(如果有的话)、预期输出以及您实际获得的输出(控制台输出、回溯等)。您提供的详细信息越多,您可能收到的答案就越多。检查FAQHow to Ask
  • @user202729 我已经添加了我现在拥有的内容。

标签: python arrays numpy


【解决方案1】:

听起来您可以为此使用scipy.distance.cdistscipy.distance.pdist。例如,要获取点Xcoords 中的点的距离:

>>> from scipy.spatial import distance
>>> X = [(35.0456, -85.2672)]
>>> coords = [(35.1174, -89.9711),
...           (35.9728, -83.9422),
...           (36.1667, -86.7833)]
>>> distance.cdist(X, coords, 'euclidean')
array([[ 4.70444794,  1.6171966 ,  1.88558331]])

pdist 类似,但只取一个数组,然后你就可以得到所有对之间的距离。

【讨论】:

    【解决方案2】:

    我正在使用这个功能:

    from scipy.spatial import distance
    
    def closest_node(node, nodes):
        closest = distance.cdist([node], nodes)
        index = closest.argmin()
        euclidean = closest[0]
        return nodes[index], euclidean[index]
    

    其中 node 是您要与称为 nodes 的点数组进行比较的空间中的单个点。它将点和欧几里德距离返回到您的原始 节点

    【讨论】:

      猜你喜欢
      • 2018-03-23
      • 1970-01-01
      • 2018-12-13
      • 1970-01-01
      • 2023-04-05
      • 2021-05-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多