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 %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