1 | %COSDISTM Distance Matrix based on Inner Products |
---|
2 | % |
---|
3 | % D = COSDISTM(A,B) |
---|
4 | % OR |
---|
5 | % D = COSDISTM(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 Dissimilarity matrix or dataset; D in [0,1] |
---|
13 | % |
---|
14 | % DESCRIPTION |
---|
15 | % Computes a distance matrix D between two sets of vectors, A and B. |
---|
16 | % Distances between vectors X and Y are derived based on their inner products |
---|
17 | % (and their relations to the cosinus of the angle between them) as: |
---|
18 | % D(X,Y) = (1 - X'*Y/(||X||*||Y||)) |
---|
19 | % |
---|
20 | % If A and B are datasets, then D is a dataset as well with the labels defined |
---|
21 | % by the labels of A and the feature labels defined by the labels of B. If A is |
---|
22 | % not a dataset, but a matrix of doubles, then D is also a matrix of doubles. |
---|
23 | % |
---|
24 | % DEFAULT |
---|
25 | % B = A |
---|
26 | % |
---|
27 | % SEE ALSO |
---|
28 | % SIMDISTM, JACSIMDISTM, CORRDISTM, LPDISTM, EUDISTM |
---|
29 | % |
---|
30 | |
---|
31 | % Copyright: Elzbieta Pekalska, ela.pekalska@googlemail.com |
---|
32 | % Faculty EWI, Delft University of Technology and |
---|
33 | % School of Computer Science, University of Manchester |
---|
34 | |
---|
35 | |
---|
36 | |
---|
37 | function D = cosdistm (A,B) |
---|
38 | bisa = nargin < 2; |
---|
39 | if bisa, |
---|
40 | B = A; |
---|
41 | end |
---|
42 | |
---|
43 | isda = isdataset(A); |
---|
44 | isdb = isdataset(B); |
---|
45 | a = +A; |
---|
46 | b = +B; |
---|
47 | |
---|
48 | [ra,ca] = size(a); |
---|
49 | [rb,cb] = size(b); |
---|
50 | |
---|
51 | if ca ~= cb, |
---|
52 | error ('Matrices should have equal numbers of columns'); |
---|
53 | end |
---|
54 | |
---|
55 | if ~bisa, |
---|
56 | ab = a * b'; |
---|
57 | a2 = sum(a.*a,2); |
---|
58 | b2 = sum(b.*b,2)'; |
---|
59 | D = ab ./ sqrt(a2(:,ones(rb,1)) .* b2(ones(ra,1),:)); |
---|
60 | else |
---|
61 | aa = a * a'; |
---|
62 | a2 = diag(aa); |
---|
63 | a3 = diag(aa)'; |
---|
64 | D = aa ./ sqrt(a2(:,ones(ra,1)) .* a3(ones(ra,1),:)); |
---|
65 | end |
---|
66 | D = (1 - D); |
---|
67 | D(find (D < eps)) = 0; |
---|
68 | |
---|
69 | |
---|
70 | % Set object labels and feature labels |
---|
71 | if xor(isda, isdb), |
---|
72 | prwarning(1,'One matrix is a dataset and the other not. ') |
---|
73 | end |
---|
74 | if isda, |
---|
75 | if isdb, |
---|
76 | D = setdata(A,D,getlab(B)); |
---|
77 | else |
---|
78 | D = setdata(A,D); |
---|
79 | end |
---|
80 | D.name = 'Distance matrix'; |
---|
81 | if ~isempty(A.name) |
---|
82 | D.name = [D.name ' for ' A.name]; |
---|
83 | end |
---|
84 | end |
---|
85 | return |
---|