改进MatLab中的ModHausdorffDist性能

时间:2012-12-24 18:34:45

标签: matlab

有什么办法可以改善这个功能的性能吗? 它包含一个嵌套的for循环。我怎样才能进行MatLab矢量化?

有什么方法可以从以下代码中删除for循环吗?

function [ mhd ] = ModHausdorffDist( A, B )


Asize = size(A);
Bsize = size(B);

% Check if the points have the same dimensions
if Asize(2) ~= Bsize(2)
    error('The dimensions of points in the two sets are not equal');
end

% Calculating the forward HD

fhd = 0;                    % Initialize forward distance to 0
for a = 1:Asize(1)          % Travel the set A to find avg of d(A,B)
    mindist = Inf;          % Initialize minimum distance to Inf
    for b = 1:Bsize(1)      % Travel set B to find the min(d(a,B))
        tempdist = norm(A(a,:)-B(b,:));
        if tempdist < mindist
            mindist = tempdist;
        end
    end
    fhd = fhd + mindist;    % Sum the forward distances
end
fhd = fhd/Asize(1);         % Divide by the total no to get average

% Calculating the reverse HD

rhd = 0;                    % Initialize reverse distance to 0
for b = 1:Bsize(1)          % Travel the set B to find avg of d(B,A)
    mindist = Inf;          % Initialize minimum distance to Inf
    for a = 1:Asize(1)      % Travel set A to find the min(d(b,A))
        tempdist = norm(A(a,:)-B(b,:));
        if tempdist < mindist
            mindist = tempdist;
        end
    end
    rhd = rhd + mindist;    % Sum the reverse distances
end
rhd = rhd/Bsize(1);         % Divide by the total no. to get average

mhd = max(fhd,rhd);         % Find the minimum of fhd/rhd as 
                            % the mod hausdorff dist


end

1 个答案:

答案 0 :(得分:0)

我会尝试这样的事情

D = bsxfun( @minus, permute( A, [3 1 2] ), permute( B, [1 3 2] ) );
D = sqrt(sum( D.^2, 3 )); % all pair-wise distances. 
% I think there is a pdist2 function that can do this computation
% of the distances. 
f = min( D, [], 1);
fhd = mean(f);
r = min( D, [], 2);
rhd = mean(r);
mhd = max( fhd, rhd );

计算距离矩阵D可以进一步改进 看着d_ij的表达式:

  

d_ij ^ 2 = || a_i || ^ 2 + || b_j || ^ 2 - 2

这意味着AB之间唯一的互动是通过Matlab知道非常有效地计算的点积。