【问题标题】:Given a list of n points, how can I generate a matrix that contains the distance from every point to every other point using numpy?给定n个点的列表,如何使用numpy生成一个包含从每个点到每个其他点的距离的矩阵?
【发布时间】:2016-10-03 15:37:12
【问题描述】:

我正在尝试在 python 中重写以下 matlab 代码:

repmat(points, 1, length(points)) - repmat(points', length(points),1);

points 是一个包含多个点的弧度值的数组。

上面的代码给了我这样的矩阵输出:

 0   1   2   0   1   2   0   1   2
-1   0   1  -1   0   1  -1   0   1
-2  -1   0  -2  -1   0  -2  -1   0
 0   1   2   0   1   2   0   1   2
-1   0   1  -1   0   1  -1   0   1
-2  -1   0  -2  -1   0  -2  -1   0
 0   1   2   0   1   2   0   1   2
-1   0   1  -1   0   1  -1   0   1
-2  -1   0  -2  -1   0  -2  -1   0

我可以很容易地操纵它来获得每个点到每个其他点的距离。

我只是想知道是否有 one liner 方法可以使用 numpy 来做到这一点?

我尝试了以下方法,但没有成功:

np.tile(points, (1, len(points))) - 
            np.tile(points.T, (len(points), 1))

有人有什么想法吗?

【问题讨论】:

  • 仅供参考,在 MATLAB 中,您实际上更喜欢使用 bsxfun 而不是 repmat:bsxfun(@minus,points,points')。 bsxfun是Suever提到的Python自动广播的MATLAB模拟。
  • @Dan 遗憾的是,没有公共链接。

标签: python matlab numpy matrix


【解决方案1】:

在 MATLAB 中,您必须使用 repmat,因为您需要 - 左侧和右侧的数组大小相同。使用 numpy,由于 numpy 的automatic broadcasting,这不一定是这种情况。相反,您可以简单地从另一个中减去一个,自动广播将创建您预期大小的结果。

# Create some example data
points = np.array([[1,2,3,4]]);

# Just subtract the transpose from points
B = points - points.T

#   array([[ 0,  1,  2,  3],
#          [-1,  0,  1,  2],
#          [-2, -1,  0,  1],
#          [-3, -2, -1,  0]])

如果points 只是一维数组,那么@JoshAdel 的答案应该适合您(它也使用广播),或者您可以将其转换为二维数组。

【讨论】:

  • 谢谢!那真的很简洁明了! @Suever
【解决方案2】:

你可能想看看scipy.spatial.pdist

但是对于构造您正在寻找的原始矩阵,如果points 只是一个一维数组:

points = np.array([1,2,3,4])
points[:,None] - points[None,:]

如果你有一个二维数组,那么@Suever 的转置方法可以很好地工作。

【讨论】:

    【解决方案3】:

    我不熟悉 matlab 代码。但是,只是试图计算从每个列向量到每个其他列向量的欧几里得距离:

    np.sqrt((np.square(A[:, None].T - A.T)).sum(axis=2))
    
    array([[ 0.,  3.,  6.,  0.,  3.,  6.,  0.,  3.,  6.],
           [ 3.,  0.,  3.,  3.,  0.,  3.,  3.,  0.,  3.],
           [ 6.,  3.,  0.,  6.,  3.,  0.,  6.,  3.,  0.],
           [ 0.,  3.,  6.,  0.,  3.,  6.,  0.,  3.,  6.],
           [ 3.,  0.,  3.,  3.,  0.,  3.,  3.,  0.,  3.],
           [ 6.,  3.,  0.,  6.,  3.,  0.,  6.,  3.,  0.],
           [ 0.,  3.,  6.,  0.,  3.,  6.,  0.,  3.,  6.],
           [ 3.,  0.,  3.,  3.,  0.,  3.,  3.,  0.,  3.],
           [ 6.,  3.,  0.,  6.,  3.,  0.,  6.,  3.,  0.]])
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-10-13
      • 2018-12-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-11-12
      • 1970-01-01
      相关资源
      最近更新 更多