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.