-
Notifications
You must be signed in to change notification settings - Fork 28
/
Copy patheucl_dist2.m
68 lines (57 loc) · 1.66 KB
/
eucl_dist2.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
% Euclidean Distance matrix.
%
% -------------------------------------------------------
% Input:
% X1: nxm data matrix (rows are samples)
% X2: nxm data matrix (rows are samples)
% opts: Structure value with the following fields:
% opts.KernelType: kernel type, choices are:
% 'Linear': (x'*y),'Gaussian': (e^{-(|x-y|^2)/2sigma^2}),
% 'Polynomial': ((x'*y)^d)
% opts.sigma: variance for Gaussian kernel
% opts.d: degree for polynomial kernel
%
% Output:
% K: nxn kernel matrix
%
% D = EuDist(fea_a,fea_b)
% fea_a: nSample_a * nFeature
% fea_b: nSample_b * nFeature
% D: nSample_a * nSample_a
% or nSample_a * nSample_b
function [D] = eucl_dist2(X1,X2,bSqrt)
if ~exist('bSqrt','var')
bSqrt = 1;
end
if (~exist('fea_b','var')) | isempty(X2)
[nSmp, nFea] = size(X1);
aa = sum(X1.*X1,2);
ab = X1*X1';
aa = full(aa);
ab = full(ab);
if bSqrt
D = sqrt(repmat(aa, 1, nSmp) + repmat(aa', nSmp, 1) - 2*ab);
D = real(D);
else
D = repmat(aa, 1, nSmp) + repmat(aa', nSmp, 1) - 2*ab;
end
D = max(D,D');
D = D - diag(diag(D));
D = abs(D);
else
[nSmp_a, nFea] = size(X1);
[nSmp_b, nFea] = size(X2);
aa = sum(X1.*X1,2);
bb = sum(X2.*X2,2);
ab = X1*X2';
aa = full(aa);
bb = full(bb);
ab = full(ab);
if bSqrt
D = sqrt(repmat(aa, 1, nSmp_b) + repmat(bb', nSmp_a, 1) - 2*ab);
D = real(D);
else
D = repmat(aa, 1, nSmp_b) + repmat(bb', nSmp_a, 1) - 2*ab;
end
D = abs(D);
end