0

I am trying to calculate the Square Euclidean Distance between each column from two matrices and store in matrix D.

im_patches is 81*60840 double

codebook is 81*456 double

SquareEuclidean = @(x, y) x'*x+y'*y-2*x'*y;

% Get N*K distance matrix D between the N patches extracted
% from the image (im patches) and the K prototypes in the codebook
D=zeros(size(im_patches,2),size(codebook, 2));

for i=1:size(im_patches,2)
    for j=1:size(codebook, 2)
        D(i,j)=SquareEuclidean(im_patches(:,i),codebook(:,j));
    end
end

However, this is very inefficient that cost more than 10 minutes in my laptop.

I am wondering is there a better way of using bsxfun. So I tried:

D2 = bsxfun(@(x,y) x'.*x+y'.*y-2.*x'.*y,im_patches,codebook);

which gives an error:

Error using bsxfun: Non-singleton dimensions of the two input arrays must match each other.

I think bsxfun or arrayfun would be a nice way of dealing such problem. But don't know the correct way of doing this.

Thank you in advance.

EBH
  • 10,350
  • 3
  • 34
  • 59
Kevin
  • 197
  • 2
  • 11

1 Answers1

1

Your loop can be reduced to:

bsxfun(@plus,sum(im_patches.'.^2,2),sum(codebook.^2)-2*im_patches.'*codebook)

In MATLAB r2016b there is no need to bsxfun:

sum(im_patches.'.^2,2)+sum(codebook.^2)-2*im_patches.'*codebook
rahnema1
  • 15,264
  • 3
  • 15
  • 27