24 lines
536 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
%
% D2: The MxN matrix with the distances
%
[~, d1] = size(X);
[~, d2] = size(Y);
if d1 ~= d2
error('X,Y column dimensions must match');
end
% debug
%X_norm = sum(X.^2, 2);
%Y_norm = sum(Y.^2, 2)';
%XY = 2 * X*Y';
D2 = max(sum(X.^2, 2) - 2 * X*Y' + sum(Y.^2, 2)', 0);
D2 = sqrt(D2);
end