-
Notifications
You must be signed in to change notification settings - Fork 3
/
EuDist2.m
59 lines (52 loc) · 1.16 KB
/
EuDist2.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
function D = EuDist2(fea_a,fea_b,bSqrt)
%EUDIST2 Efficiently Compute the Euclidean Distance Matrix by Exploring the
%Matlab matrix operations.
%
% 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
%
% Examples:
%
% a = rand(500,10);
% b = rand(1000,10);
%
% A = EuDist2(a); % A: 500*500
% D = EuDist2(a,b); % D: 500*1000
%
% version 2.1 --November/2011
% version 2.0 --May/2009
% version 1.0 --November/2005
%
% Written by Deng Cai (dengcai AT gmail.com)
if ~exist('bSqrt','var')
bSqrt = 1;
end
if (~exist('fea_b','var')) || isempty(fea_b)
aa = sum(fea_a.*fea_a,2);
ab = fea_a*fea_a';
if issparse(aa)
aa = full(aa);
end
D = bsxfun(@plus,aa,aa') - 2*ab;
D(D<0) = 0;
if bSqrt
D = sqrt(D);
end
D = max(D,D');
else
aa = sum(fea_a.*fea_a,2);
bb = sum(fea_b.*fea_b,2);
ab = fea_a*fea_b';
if issparse(aa)
aa = full(aa);
bb = full(bb);
end
D = bsxfun(@plus,aa,bb') - 2*ab;
D(D<0) = 0;
if bSqrt
D = sqrt(D);
end
end