# 用numpy计算距离矩阵

##### 问题描述投票：1回答：2

``````array([[[0, 0],
[1, 0],
[2, 0],
[3, 0]],

[[0, 1],
[1, 1],
[2, 1],
[3, 1]],

[[0, 2],
[1, 2],
[2, 2],
[3, 2]],

[[0, 3],
[1, 3],
[2, 3],
[3, 3]],

[[0, 4],
[1, 4],
[2, 4],
[3, 4]]])
``````

``````pos_goal = np.array([1,2])
dist_matrix = np.zeros(l_arr.shape[:2])
for i, line in enumerate(l_arr):
for j, pos in enumerate(line):
dist_matrix[i,j] = np.linalg.norm(pos - pos_goal)

dist_matrix
``````

``````array([[ 2.23606798,  2.        ,  2.23606798,  2.82842712],
[ 1.41421356,  1.        ,  1.41421356,  2.23606798],
[ 1.        ,  0.        ,  1.        ,  2.        ],
[ 1.41421356,  1.        ,  1.41421356,  2.23606798],
[ 2.23606798,  2.        ,  2.23606798,  2.82842712]])
``````

python arrays numpy matrix
##### 2个回答
2

``````from scipy.spatial import distance
dist_matrix = distance.cdist(l_arr.reshape(-1, 2), [pos_goal]).reshape(l_arr.shape[:2])
``````

2

`np.linalg.norm`函数采用`axis`参数，因此您需要：

``````In [6]: np.linalg.norm(l_arr - pos_goal, axis=2)
Out[6]:
array([[ 2.23606798,  2.        ,  2.23606798,  2.82842712],
[ 1.41421356,  1.        ,  1.41421356,  2.23606798],
[ 1.        ,  0.        ,  1.        ,  2.        ],
[ 1.41421356,  1.        ,  1.41421356,  2.23606798],
[ 2.23606798,  2.        ,  2.23606798,  2.82842712]])
``````

``````In [7]: np.linalg.norm(l_arr - pos_goal, axis=-1)
Out[7]:
array([[ 2.23606798,  2.        ,  2.23606798,  2.82842712],
[ 1.41421356,  1.        ,  1.41421356,  2.23606798],
[ 1.        ,  0.        ,  1.        ,  2.        ],
[ 1.41421356,  1.        ,  1.41421356,  2.23606798],
[ 2.23606798,  2.        ,  2.23606798,  2.82842712]])
``````

``````In [11]: l_arr - pos_goal
Out[11]:
array([[[-1, -2],
[ 0, -2],
[ 1, -2],
[ 2, -2]],

[[-1, -1],
[ 0, -1],
[ 1, -1],
[ 2, -1]],

[[-1,  0],
[ 0,  0],
[ 1,  0],
[ 2,  0]],

[[-1,  1],
[ 0,  1],
[ 1,  1],
[ 2,  1]],

[[-1,  2],
[ 0,  2],
[ 1,  2],
[ 2,  2]]])
``````