问题描述
在Matlab中,存在pdist2
命令.给定矩阵mx2
和矩阵nx2
,矩阵的每一行代表一个2d
点.现在,我想创建一个mxn
矩阵,以使(i,j)
元素表示从mx2
矩阵的i
点到nx2
矩阵的第c8点的距离.我只需调用命令pdist2(M,N)
.
In Matlab there exists the pdist2
command. Given the matrix mx2
and the matrix nx2
, each row of matrices represents a 2d
point. Now I want to create a mxn
matrix such that (i,j)
element represents the distance from i
th point of mx2
matrix to j
th point of nx2
matrix. I simply call the command pdist2(M,N)
.
我正在python中寻找替代方法.我当然可以编写2个for循环,但是由于我正在使用2个numpy数组,因此使用for循环并不总是最好的选择.在python Universe中是否有针对此的优化命令?基本上,我要用Python代替MATLAB的pdist2
.
I am looking for an alternative to this in python. I can of course write 2 for loops but since I am working with 2 numpy arrays, using for loops is not always the best choice. Is there an optimized command for this in the python universe? Basically I am asking for python alternative to MATLAB's pdist2
.
推荐答案
您正在寻找 cdist scipy函数.它将计算两组n维矩阵之间的成对距离(默认情况下为欧式).
You're looking for the cdist scipy function. It will calculate the pair-wise distances (euclidean by default) between two sets of n-dimensional matrices.
from scipy.spatial.distance import cdist
import numpy as np
X = np.arange(10).reshape(-1,2)
Y = np.arange(10).reshape(-1,2)
cdist(X, Y)
[[ 0. 2.82842712 5.65685425 8.48528137 11.3137085 ]
[ 2.82842712 0. 2.82842712 5.65685425 8.48528137]
[ 5.65685425 2.82842712 0. 2.82842712 5.65685425]
[ 8.48528137 5.65685425 2.82842712 0. 2.82842712]
[ 11.3137085 8.48528137 5.65685425 2.82842712 0. ]]
这篇关于Python替代品,用于计算两组2d点之间的成对距离的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!