-
Notifications
You must be signed in to change notification settings - Fork 9
/
euclidean.m
executable file
·72 lines (61 loc) · 1.9 KB
/
euclidean.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
function d = euclidean(a,b,df)
% EUCLIDEAN - computes Euclidean distance matrix
%
% E = euclidean(A,B)
%
% A - (DxM) matrix
% B - (DxN) matrix
% df = 1, force diagonals to be zero; 0 (default), do not force
%
% Returns:
% E - (MxN) Euclidean distances between vectors in A and B
%
%
% Description :
% This fully vectorized (VERY FAST!) m-file computes the
% Euclidean distance between two vectors by:
%
% ||A-B|| = sqrt ( ||A||^2 + ||B||^2 - 2*A.B )
%
% Example :
% A = rand(400,100); B = rand(400,200);
% d = distance(A,B);
% Author : Roland Bunschoten
% University of Amsterdam
% Intelligent Autonomous Systems (IAS) group
% Kruislaan 403 1098 SJ Amsterdam
% tel.(+31)20-5257524
% Last Rev : Wed Oct 20 08:58:08 MET DST 1999
% Tested : PC Matlab v5.2 and Solaris Matlab v5.3
% Copyright notice: You are free to modify, extend and distribute
% this code granted that the author of the original code is
% mentioned as the original author of the code.
% Fixed by JBT (3/18/00) to work for 1-dimensional vectors
% and to warn for imaginary numbers. Also ensures that
% output is all real, and allows the option of forcing diagonals to
% be zero.
if (nargin < 2)
error('Not enough input arguments');
end
if (nargin < 3)
df = 0; % by default, do not force 0 on the diagonal
end
if (size(a,1) ~= size(b,1))
error('A and B should be of same dimensionality');
end
if ~(isreal(a)*isreal(b))
disp('Warning: running distance.m with imaginary numbers. Results may be off.');
end
if (size(a,1) == 1)
a = [a; zeros(1,size(a,2))];
b = [b; zeros(1,size(b,2))];
end
aa=sum(a.*a); bb=sum(b.*b); ab=a'*b;
d = sqrt(repmat(aa',[1 size(bb,2)]) + repmat(bb,[size(aa,2) 1]) - 2*ab);
% make sure result is all real
d = real(d);
% force 0 on the diagonal?
if (df==1)
d = d.*(1-eye(size(d)));
end