在计算欧几里德距离时,您经常可以使用的一个巧妙技巧是修改您的算法以使用平方欧几里德距离 - 这消除了不必要的昂贵的平方根函数,例如,如果您只想找到最大的或一组中的最小距离。
所以内循环可能变成:
distSquared(j) = sum((des1(i, :) - des2(j, :)).^2);
在你的情况下,改变的棘手事情是这条线
if (vals(1) < distRatio * vals(2))
这相当于
if (vals(1)^2 < (distRatio * vals(2))^2)
或者
if (vals(1)^2 < (distRatio^2) * (vals(2)^2))
如果您从而distSquared
不是获取值eucl
,那么您可以使用
if (valSquared(1) < (distRatio^2) * valSquared(2))
最后,您可以通过像这样重写减法来取出内部循环:
countRowsDes2 = size(des2, 1); % this line outside the loop
%... now inside the loop
des1expand = repmat(des1(i, :), countRowsDes2, 1); % copy this row
distSquared = sum((des1expand - des2).^2, 2); % sum horizontally
我曾经在哪里repmat
复制 row des1(i, :)
,并sum
使用第二个维度参数在水平维度上工作。
把它们放在一起
distRatio = 0.5;
distRatioSq = distRatio^2; % distance ratio squared
countRowsDes1 = size(des1, 1); % number of rows in des1
countRowsDes2 = size(des2, 1); % number of rows in des2
match = zeros(countRowsDes1, 1); % pre-initialize with zeros
for i = i:size(des1, 1)
des1expand = repmat(des1(i, :), countRowsDes2, 1); % copy row i of des1
distSquared = sum((des1expand - des2).^2, 2); % sum horizontally
[valsSquared, index] = sort(distSquared);
if (valsSquared(1) < distRatioSq * valsSquared(2))
match(i) = index(1);
% else zero by initialization
end