1 | %CORRTR Correct square distance matrix for the violation of the triangle inequality |
---|
2 | % |
---|
3 | % DC = CORRTR(D) |
---|
4 | % |
---|
5 | % INPUT |
---|
6 | % D NxN symmetric dissimilarity matrix or dataset |
---|
7 | % |
---|
8 | % OUTPUT |
---|
9 | % DC Dissimilarity matrix/dataset with all entries corrected where the triangle inequality is violated |
---|
10 | % |
---|
11 | |
---|
12 | % Copyright: R.P.W. Duin, r.p.w.duin@prtools.org, Ela Pekalska, ela.pekalska@googlemail.com |
---|
13 | % Faculty EWI, Delft University of Technology |
---|
14 | % P.O. Box 5031, 2600 GA Delft, The Netherlands |
---|
15 | |
---|
16 | function d = corrtr(x) |
---|
17 | |
---|
18 | d = +x; |
---|
19 | [n,m] = size(d); |
---|
20 | if n ~= m |
---|
21 | error('Dissimilarity matrix should be square') |
---|
22 | end |
---|
23 | |
---|
24 | d = min(d,d'); |
---|
25 | d(1:n+1:end) = 0; |
---|
26 | |
---|
27 | for j=1:n-1 % correct the upper triangle, top down |
---|
28 | r1 = d(:,j); |
---|
29 | r2 = d(j,j+1:n); |
---|
30 | % M checks the triangle ineqaulities; all elements of M are |
---|
31 | % positive or zero if this holds. |
---|
32 | % M = repmat(r1,1,n-j) - d(:,j+1:n) + repmat(r2,n,1); |
---|
33 | d(:,j+1:n) = min(repmat(r1,1,n-j) + repmat(r2,n,1), d(:,j+1:n)); |
---|
34 | end |
---|
35 | d = min(d,d'); % correct the bottom triangle as well |
---|
36 | |
---|
37 | for j=n:-1:2 % correct the bottom triangle, bottom up |
---|
38 | r1 = d(:,j); |
---|
39 | r2 = d(j,1:j-1); |
---|
40 | % M checks the triangle ineqaulities; all elements of M are |
---|
41 | % positive or zero if this holds. |
---|
42 | % M = repmat(r1,1,n-j) - d(:,j+1:n) + repmat(r2,n,1); |
---|
43 | d(:,1:j-1) = min(repmat(r1,1,j-1) + repmat(r2,n,1), d(:,1:j-1)); |
---|
44 | end |
---|
45 | d = min(d,d'); % correct the upper triangle as well |
---|
46 | |
---|
47 | d = setdata(x,d); |
---|
48 | |
---|
49 | return |
---|