是否有一种更有效的方法来生成numpy中的距离矩阵 [英] Is there a more efficient way to generate a distance matrix in numpy
问题描述
我想知道在给定矩阵的H x W和起始索引位置的情况下,是否存在更直接,更有效的方法来生成距离矩阵.
I was wondering if there is a more straight forward, more efficient way of generating a distance matrix given the H x W of the matrix, and the starting index location.
为简单起见,让我们以起始点为(0,0)的3x3矩阵为例.因此,要生成的距离矩阵为:
For simplicity lets take a 3x3 matrix where the starting point is (0,0). Thus, the distance matrix to be generated is:
[[ 0. 1. 2. ]
[ 1. 1.41421356 2.23606798]
[ 2. 2.23606798 2.82842712]]
索引(0,1)距离为1,而索引(2,2)距离为2.828.
Index (0,1) is 1 distance away, while index (2,2) is 2.828 distance away.
我到目前为止的代码如下:
The code I have so far is below:
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总是用我通常不会想到的一些技巧使我感到惊讶,因此我想知道在这种情况下是否存在这种技巧.谢谢
This is pretty efficient already, I think. But numpy always surprise me with some tricks that I usually never think of, so I was wondering if there exist one in this scenario. Thanks
推荐答案
您可以使用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)
:
to calculate the distance between every point on a grid to a fixed point (x, y)
:
x, y = np.ogrid[0:3, 0:3]
np.hypot(x - 2, y - 2)
这篇关于是否有一种更有效的方法来生成numpy中的距离矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!