source: distools/cosdistm.m @ 127

Last change on this file since 127 was 79, checked in by bduin, 11 years ago
File size: 1.8 KB
RevLine 
[10]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
[79]12%   D   NxM Dissimilarity matrix or prdataset; D in [0,1]
[10]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
37function D = cosdistm (A,B)
38bisa = nargin < 2;
39if bisa,
40  B = A;
41end
42
43isda = isdataset(A);
44isdb = isdataset(B);
45a = +A;
46b = +B;
47
48[ra,ca] = size(a);
49[rb,cb] = size(b);
50
51if ca ~= cb,
52  error ('Matrices should have equal numbers of columns');
53end
54
55if ~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),:));
60else
61  aa = a * a';
62  a2 = diag(aa);
63  a3 = diag(aa)';
64  D  = aa ./ sqrt(a2(:,ones(ra,1)) .* a3(ones(ra,1),:));
65end
66D = (1 - D);
67D(find (D < eps)) = 0;
68
69
70% Set object labels and feature labels
71if xor(isda, isdb),
72  prwarning(1,'One matrix is a dataset and the other not. ')
73end
74if 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
84end
85return
Note: See TracBrowser for help on using the repository browser.