python - How to get euclidean distance on a 3x3x3 array in numpy -
say have (3,3,3) array this.
array([[[1, 1, 1], [1, 1, 1], [0, 0, 0]], [[2, 2, 2], [2, 2, 2], [2, 2, 2]], [[3, 3, 3], [3, 3, 3], [1, 1, 1]]])
how 9 values corresponding euclidean distance between each vector of 3 values , zeroth values?
such doing numpy.linalg.norm([1,1,1] - [1,1,1])
2 times, , doing norm([0,0,0] - [0,0,0])
, , norm([2,2,2] - [1,1,1])
2 times, norm([2,2,2] - [0,0,0])
, norm([3,3,3] - [1,1,1])
2 times, , norm([1,1,1] - [0,0,0])
.
any ways vectorize this? want store distances in (3,3,1) matrix.
the result be:
array([[[0. ], [0. ], [0. ]], [[1.73], [1.73], [3.46]] [[3.46], [3.46], [1.73]]])
keepdims
argument added in numpy 1.7, can use keep sum axis:
np.sum((x - [1, 1, 1])**2, axis=-1, keepdims=true)**0.5
the result is:
[[[ 0. ] [ 0. ] [ 0. ]] [[ 1.73205081] [ 1.73205081] [ 1.73205081]] [[ 3.46410162] [ 3.46410162] [ 0. ]]]
edit
np.sum((x - x[0])**2, axis=-1, keepdims=true)**0.5
the result is:
array([[[ 0. ], [ 0. ], [ 0. ]], [[ 1.73205081], [ 1.73205081], [ 3.46410162]], [[ 3.46410162], [ 3.46410162], [ 1.73205081]]])
Comments
Post a Comment