19 lines
466 B
Matlab

function [D2] = dist2(X, Y)
% Calculates the squares of the distances of X and Y
%
% X: A mxd array with m d-dimentional points
% Y: A nxd array with n d-dimentional points
% d: Must be the same
[~, d1] = size(X);
[~, d2] = size(Y);
if d1 ~= d2
error('X,Y column dimensions must match');
end
%D2 = sqrt((X.^2)*ones(d,m) -2*X*Y' + ones(n,d)*(Y.^2)');
D2 = max(sum(X.^2, 2) - 2 * X*Y' + sum(Y.^2, 2)', 0);
D2 = sqrt(D2);
end