MATLAB: Computing euclidean distance in an efficient way?

删除回忆录丶 提交于 2021-02-11 12:13:24

问题


What I am currently doing is computing the euclidean distance between all elements in a vector (the elements are pixel locations in a 2D image) to see if the elements are close to each other. I create a reference vector that takes on the value of each index within the vector incrementally. The euclidean distance between the reference vector and all the elements in the pixel location vector is computed using the MATLAB function "pdist2" and the result is applied to some conditions; however, upon running the code, this function seems to be taking the longest to compute (i.e. for one run, the function was called upon 27,245 times and contributed to about 54% of the overall program's run time). Is there a more efficient method to do this and speed up the program?

[~, n] = size(xArray); %xArray and yArray are same size
%Pair the x and y coordinates of the interest pixels
pairLocations = [xArray; yArray].';
%Preallocate cells with the max amount (# of interest pixels)
p = cell(1,n);

for i = 1:n
    ref = [xArray(i), yArray(i)];
    d = pdist2(ref,pairLocations,'euclidean');
    d = d < dTh;
    d = find(d==1);
    [~,k] = size(d);
    if (k >= num)
        p{1,i} = d;
    end
end

回答1:


For squared Euclidean distance, there is a trick using matrix dot product:

||a-b||² = <a-b, a-b> = ||a||² - 2<a,b> + ||b||²

Let C = [xArray; yArray]; a 2×n matrix of all locations, then

n2 = sum(C.^2); % sq norm of coordinates
D  = bsxfun(@plus, n2, n2.') - 2 * C.' * C;

Now D(ii,jj) holds the square distance between point ii and point jj. Should run quite quickly.



来源:https://stackoverflow.com/questions/40480230/matlab-computing-euclidean-distance-in-an-efficient-way

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!