Matlab dist函数 对应 python 代码
Matlab 中的dist
dist()函数,求矩阵和向量之间的欧式距离
A:nd的矩阵
B: 1d的矩阵
C = dist(A,B) :得到的也是n*d的矩阵
Python 中现有的求距离函数
python 的 cdist和pdist 都不对应Matlab的dist()函数
cdist(A,B) 得到的是n*1 的向量
cdist 与pdist 区别
| distance.cdist()方法 | distance.pdist()方法 | |
|---|---|---|
| 输入 | distance.cdist()方法 distance.pdist()方法输入 输入两个距离(A、B),计算方法是X中的点一次与Y中的点求距离。 | 输入一个数组点(X),里面的元素反复对比求距离(i -> i+1距离,i -> i+2距离,i -> i+3 距离…) |
| 输出 | 返回 n形状*1形状的向量 | 返回一个列表 |
Python 实现Matlab中的dist
python 版的dist 距离函数(求欧式距离)如下:
## matlab 中的 dist
import numpy as np
def mdist(w,p):
S,R = w.shape
Q = p.shape[1]
z = iDistApplyCPU(w,p,S,Q)
return z
def iDistApplyCPU(w,p,S,Q):
z = np.zeros((S,Q))
if (Q<S):
pt = p.T
for q in range(Q):
z[:,q] = np.sum((w-pt[q,:])**2, 1)
else:
wt = w.T
for i in range(S):
z[i,:] = np.sum((wt[:,i]-p)**2, 0)
z = np.sqrt(z)
return z
A:nd的矩阵
B: 1d的矩阵
C = mdist(A,B) : 也会得到的像Matlab中dist,是n*d的矩阵
参考:
本文介绍如何将Matlab中的dist函数转换为Python代码,详细解释了Python中对应的mdist函数实现过程,以及与cdist和pdist的区别。
2410

被折叠的 条评论
为什么被折叠?



