1 | %EUDISTM Euclidean Distance Matrix
|
---|
2 | %
|
---|
3 | % D = EUDISTM(A,B)
|
---|
4 | % OR
|
---|
5 | % D = EUDISTM(A)
|
---|
6 | %
|
---|
7 | % INPUT
|
---|
8 | % A NxK Matrix or dataset
|
---|
9 | % B MxK Matrix or dataset (optional; default: B = A)
|
---|
10 | %
|
---|
11 | % OUTPUT
|
---|
12 | % D NxM Euclidean distance dataset or matrix
|
---|
13 | %
|
---|
14 | % DESCRIPTION
|
---|
15 | % Computation of the Euclidean distance matrix D between two sets of vectors
|
---|
16 | % A and B. If A and B are datasets, then D is a dataset as well with the labels
|
---|
17 | % defined by the labels of A and the feature labels defined by the labels of B.
|
---|
18 | % If A is not a dataset, but a matrix of doubles then D is also a matrix of
|
---|
19 | % doubles.
|
---|
20 | %
|
---|
21 | % NOTE
|
---|
22 | % EUDISTM(A,B) is equivalent to SQRT(DISTM(A,B)).
|
---|
23 | %
|
---|
24 | % DEFAULT
|
---|
25 | % B = A
|
---|
26 | %
|
---|
27 | % SEE ALSO
|
---|
28 | % DATASETS, DISTM, PROXM
|
---|
29 |
|
---|
30 | % Copyright: Elzbieta Pekalska, ela.pekalska@googlemail.com
|
---|
31 | % Faculty EWI, Delft University of Technology and
|
---|
32 | % School of Computer Science, University of Manchester
|
---|
33 |
|
---|
34 |
|
---|
35 | function D = eudistm(A,B)
|
---|
36 | bisa = nargin < 2;
|
---|
37 | if bisa,
|
---|
38 | B = A;
|
---|
39 | end
|
---|
40 |
|
---|
41 | isda = isdataset(A);
|
---|
42 | isdb = isdataset(B);
|
---|
43 | a = +A;
|
---|
44 | b = +B;
|
---|
45 |
|
---|
46 | [ra,ca] = size(a);
|
---|
47 | [rb,cb] = size(b);
|
---|
48 | if ca ~= cb,
|
---|
49 | error ('Matrices should have equal numbers of columns');
|
---|
50 | end
|
---|
51 |
|
---|
52 |
|
---|
53 | % The order of operations below is good for the accuracy.
|
---|
54 | D = ones(ra,1)*sum(b'.*b',1);
|
---|
55 | D = D + sum(a'.*a',1)'*ones(1,rb);
|
---|
56 | D = D - 2 .*(+a)*(+b)';
|
---|
57 |
|
---|
58 | % Check for a numerical inaccuracy
|
---|
59 | D(find(D<eps)) = 0;
|
---|
60 |
|
---|
61 | D = sqrt(D);
|
---|
62 |
|
---|
63 | % Take care of symmetric distance matrix
|
---|
64 | if bisa & ra == rb,
|
---|
65 | D = 0.5*(D + D');
|
---|
66 | D([1:ra+1:ra^2]) = 0;
|
---|
67 | end
|
---|
68 |
|
---|
69 | % Set object labels and feature labels
|
---|
70 | if xor(isda, isdb),
|
---|
71 | prwarning(1,'One matrix is a dataset and the other not. ')
|
---|
72 | end
|
---|
73 | if isda,
|
---|
74 | if isdb,
|
---|
75 | D = setdata(A,D,getlab(B));
|
---|
76 | else
|
---|
77 | D = setdata(A,D);
|
---|
78 | end
|
---|
79 | D.name = 'Distance matrix';
|
---|
80 | if ~isempty(A.name)
|
---|
81 | D.name = [D.name ' for ' A.name];
|
---|
82 | end
|
---|
83 | end
|
---|
84 | return
|
---|