【发布时间】:2018-06-19 03:42:15
【问题描述】:
我想知道在给定矩阵的 H x W 和起始索引位置的情况下,是否有更直接、更有效的方法来生成距离矩阵。
为简单起见,我们采用一个 3x3 矩阵,其起点为 (0,0)。因此,要生成的距离矩阵为:
[[ 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 总是用一些我通常不会想到的技巧让我感到惊讶,所以我想知道在这种情况下是否存在这样的技巧。谢谢
【问题讨论】:
标签: python numpy matrix euclidean-distance