0

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
Mike S
  • 13
  • 4
  • First of all, `pdist2` can get a matrix as input (it doesnt have to be the point in a for loop). However, from your code, i understand that you wish to find only the pixel indexes with distance of 1 from your reference pixel. so, i think the overall solution might be much simpler (simplly add and subtract 1 from the x and y indexes)... – itzik Ben Shabat Nov 08 '16 at 06:46
  • I am not trying to find the pixel indices that have a distance of 1 from the threshold. I am setting the d vector to binary based on the result of the condition (d = d < dTh) that the distance of a pixel's index is less than a certain set threshold value for the distance from the reference, then finding at which index this occurs in d. – Mike S Nov 08 '16 at 07:20

1 Answers1

2

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.

Rody Oldenhuis
  • 37,726
  • 7
  • 50
  • 96
Shai
  • 111,146
  • 38
  • 238
  • 371