Python替代品,用于计算两组2d点之间的成对距离 [英] Python alternative for calculating pairwise distance between two sets of 2d points

查看:105
本文介绍了Python替代品,用于计算两组2d点之间的成对距离的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在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 ith point of mx2 matrix to jth 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.

推荐答案

您正在寻找

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点之间的成对距离的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆