给出两组d
维度点。如何在Matlab中最有效地计算成对平方欧氏距离矩阵?
符号:
第一组由(numA,d)
- 矩阵A
给出,第二组由(numB,d)
- 矩阵B
给出。得到的距离矩阵的格式应为(numA,numB)
。
示例点:
d = 4; % dimension
numA = 100; % number of set 1 points
numB = 200; % number of set 2 points
A = rand(numA,d); % set 1 given as matrix A
B = rand(numB,d); % set 2 given as matrix B
答案 0 :(得分:19)
此处通常给出的答案基于bsxfun
(参见例如[1])。我提出的方法基于矩阵乘法,结果比我能找到的任何类似算法快得多:
helpA = zeros(numA,3*d);
helpB = zeros(numB,3*d);
for idx = 1:d
helpA(:,3*idx-2:3*idx) = [ones(numA,1), -2*A(:,idx), A(:,idx).^2 ];
helpB(:,3*idx-2:3*idx) = [B(:,idx).^2 , B(:,idx), ones(numB,1)];
end
distMat = helpA * helpB';
请注意:
对于常量d
,可以用硬编码实现替换for
- 循环,例如。
helpA(:,3*idx-2:3*idx) = [ones(numA,1), -2*A(:,1), A(:,1).^2, ... % d == 2
ones(numA,1), -2*A(:,2), A(:,2).^2 ]; % etc.
<强>评价为:强>
%% create some points
d = 2; % dimension
numA = 20000;
numB = 20000;
A = rand(numA,d);
B = rand(numB,d);
%% pairwise distance matrix
% proposed method:
tic;
helpA = zeros(numA,3*d);
helpB = zeros(numB,3*d);
for idx = 1:d
helpA(:,3*idx-2:3*idx) = [ones(numA,1), -2*A(:,idx), A(:,idx).^2 ];
helpB(:,3*idx-2:3*idx) = [B(:,idx).^2 , B(:,idx), ones(numB,1)];
end
distMat = helpA * helpB';
toc;
% compare to pdist2:
tic;
pdist2(A,B).^2;
toc;
% compare to [1]:
tic;
bsxfun(@plus,dot(A,A,2),dot(B,B,2)')-2*(A*B');
toc;
% Another method: added 07/2014
% compare to ndgrid method (cf. Dan's comment)
tic;
[idxA,idxB] = ndgrid(1:numA,1:numB);
distMat = zeros(numA,numB);
distMat(:) = sum((A(idxA,:) - B(idxB,:)).^2,2);
toc;
结果:
Elapsed time is 1.796201 seconds.
Elapsed time is 5.653246 seconds.
Elapsed time is 3.551636 seconds.
Elapsed time is 22.461185 seconds.
有关w.r.t的详细评估数据点的维度和数量遵循以下讨论(@comments)。事实证明,在不同的环境中应该首选不同的算法。在非时间紧急情况下,只需使用pdist2
版本。
进一步发展: 人们可以考虑用基于相同原理的任何其他度量来替换平方的欧几里得:
help = zeros(numA,numB,d);
for idx = 1:d
help(:,:,idx) = [ones(numA,1), A(:,idx) ] * ...
[B(:,idx)' ; -ones(1,numB)];
end
distMat = sum(ANYFUNCTION(help),3);
然而,这非常耗时。用d
二维矩阵替换较小的help
三维矩阵d
可能很有用。特别是对于d = 1
,它提供了一种通过简单矩阵乘法计算成对差异的方法:
pairDiffs = [ones(numA,1), A ] * [B'; -ones(1,numB)];
您还有其他想法吗?
答案 1 :(得分:1)
对于平方欧几里德距离,也可以使用以下公式
||a-b||^2 = ||a||^2 + ||b||^2 - 2<a,b>
<a,b>
是a
和b
nA = sum( A.^2, 2 ); %// norm of A's elements
nB = sum( B.^2, 2 ); %// norm of B's elements
distMat = bsxfun( @plus, nA, nB' ) - 2 * A * B' ;
最近,我已经told从R2016b开始,这种计算平方欧几里德距离的方法比接受的方法更快。