[英]Is there a more efficient way to generate a distance matrix in numpy
我想知道在给定矩阵的H x W和起始索引位置的情况下,是否存在更直接,更有效的方法来生成距离矩阵。
为简单起见,让我们以起始点为(0,0)的3x3矩阵为例。 因此,要生成的距离矩阵为:
[[ 0. 1. 2. ]
[ 1. 1.41421356 2.23606798]
[ 2. 2.23606798 2.82842712]]
索引(0,1)距离为1,而索引(2,2)距离为2.828。
我到目前为止的代码如下:
def get_distances(start, height, width):
matrix = np.zeros((height, width), dtype=np.float16)
indexes = [(y, x) for y, row in enumerate(matrix) for x, val in enumerate(row)]
to_points = np.array(indexes)
start_point = np.array(start)
distances = np.linalg.norm(to_points - start_point, ord=2, axis=1.)
return distances.reshape((height, width))
height = 3
width = 3
start = [0,0]
distance_matrix = get_distances(start, height, width)
我认为这已经非常有效了。 但是numpy总是用我通常不会想到的一些技巧使我感到惊讶,因此我想知道这种情况下是否存在。 谢谢
您可以使用hypot()
并广播:
import numpy as np
x = np.arange(3)
np.hypot(x[None, :], x[:, None])
或outer
方法:
np.hypot.outer(x, x)
结果:
array([[ 0. , 1. , 2. ],
[ 1. , 1.41421356, 2.23606798],
[ 2. , 2.23606798, 2.82842712]])
计算网格上每个点到固定点(x, y)
的距离:
x, y = np.ogrid[0:3, 0:3]
np.hypot(x - 2, y - 2)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.