最近做实验时,遇到一个问题:
给定一个矩阵A(m*n),A的每一行对应一个样本,每列对应该样本的特征,则A存储的就是m个样本,每个样本是个n维的向量。现在想计算这m个样本相互之间的欧式距离,除了直接的两层循环实现之外,在网上搜索发现matlab已经提供了类似功能的函数:pdist和pdist2(前者计算一个向量自身的距离矩阵,后者计算两个向量之间的距离矩阵;pdist2返回是n*n的距离矩阵,pdist则返回距离矩阵的下三角串联形式)
下面这是pdist2帮助说明的节选:
pdist2 Pairwise distance between two sets of observations.
D = pdist2(X,Y) returns a matrix D containing the Euclidean distances
between each pair of observations in the MX-by-N data matrix X and
MY-by-N data matrix Y. Rows of X and Y correspond to observations,
and columns correspond to variables. D is an MX-by-MY matrix, with the
(I,J) entry equal to distance between observation I in X and
observation J in Y.
该函数除了可计算欧式距离外,还可通过参数设置计算其他几种常见距离。
对于我的问题可这样实现:vdis=pdist2(A,A)
转载本文请联系原作者获取授权,同时请注明本文来自王海军科学网博客。
链接地址:http://blog.sciencenet.cn/blog-791749-691557.html
上一篇:matlab将某个文件夹连同里面的子文件夹设置为路径
下一篇:PSNR对不同的数据类型结果也不相同