


zDistance(A,B) finds the Euclidean distances between the rows of A and of B


0001 % zDistance(A,B) finds the Euclidean distances between the rows of A and of B 0002 0003 function [D] = zDistance(A,B) 0004 0005 [M,t] = size(A); 0006 0007 if nargin < 2, 0008 0009 G = A * A'; % inner products of rows of A 0010 0011 a = diag(G); % sums of squares of each row of A 0012 0013 X = repmat(a,1,M); % repeat a in each row 0014 0015 D = sqrt(X + X' - 2*G); % |u-v| = |u|^2 + |v|^2 - 2 u . v 0016 0017 else 0018 0019 a = sum((A.*A)'); % sum of squares of each row of A 0020 b = sum((B.*B)'); % sum of squares of each row of B 0021 0022 M = length(a); % number of rows in A 0023 N = length(b); % number of rows in B 0024 0025 X = repmat(b,M,1); % repeat a in each row 0026 Y = repmat(a',1,N); % repeat b in each column 0027 0028 G = A * B'; % inner products of rows of A 0029 0030 D = sqrt(X + Y - 2*G); % |u-v| = |u|^2 + |v|^2 - 2 u . v 0031 0032 end