square distance matrix for X and Y case 1: dd = sq_distance(X,Y) dd = sq_distance(X,Y,flg) flg = 0 X : (D x M) matrix Y : (D x N) matrix case 2: dd = sq_distance(X,Y,flg) flg = 1 X : (M x D) matrix Y : (N x D) matrix dd = (X-Y)^2 = X^2 + Y^2 - 2*X*Y : (M x N) square distance matrix D : space dimension of X and Y M, N : number of points in X and Y 2013-7-05 Masa-aki Sato Copyright (C) 2011, ATR All Rights Reserved. License : New BSD License(see VBMEG_LICENSE.txt)
0001 function dd = sq_distance(X,Y,flg) 0002 % square distance matrix for X and Y 0003 % case 1: 0004 % dd = sq_distance(X,Y) 0005 % dd = sq_distance(X,Y,flg) 0006 % flg = 0 0007 % X : (D x M) matrix 0008 % Y : (D x N) matrix 0009 % case 2: 0010 % dd = sq_distance(X,Y,flg) 0011 % flg = 1 0012 % X : (M x D) matrix 0013 % Y : (N x D) matrix 0014 % 0015 % dd = (X-Y)^2 = X^2 + Y^2 - 2*X*Y : (M x N) square distance matrix 0016 % D : space dimension of X and Y 0017 % M, N : number of points in X and Y 0018 % 0019 % 0020 % 2013-7-05 Masa-aki Sato 0021 % 0022 % Copyright (C) 2011, ATR All Rights Reserved. 0023 % License : New BSD License(see VBMEG_LICENSE.txt) 0024 0025 if nargin==2 || flg==0 0026 if (size(X,1) ~= size(Y,1)) 0027 error('dimension of X and Y are different '); 0028 end 0029 0030 XX = sum(X.^2,1); % 1 x M 0031 YY = sum(Y.^2,1); % 1 x N 0032 XY = -2*X'*Y; % M x N 0033 0034 % (X-Y)^2 = X^2 + Y^2 - 2*X'*Y 0035 dd = vb_repadd( XY, XX'); 0036 dd = vb_repadd( dd, YY); 0037 else 0038 if (size(X,2) ~= size(Y,2)) 0039 error('dimension of X and Y are different '); 0040 end 0041 0042 XX = sum(X.^2,2); % M x 1 0043 YY = sum(Y.^2,2); % N x 1 0044 XY = -2*X*Y'; % M x N 0045 0046 % (X-Y)^2 = X^2 + Y^2 - 2*X*Y' 0047 dd = vb_repadd( XY, XX); 0048 dd = vb_repadd( dd, YY'); 0049 end 0050 0051 dd = max(dd,0);