User defined distance function

3 views (last 30 days)
MByk
MByk on 2 Jul 2017
Commented: MByk on 2 Jul 2017
I'am trying to calculate Canberra distance (formula of the Canberra distance sum(a-b/|a|+|b|)) by defining a custom distance function but it is not working correctly. Would you help correcting my function? Thank you.
r = [0 3 4 5;7 6 3 -1;-1 1 -1 1;2 3 4 5];
dist = squareform(pdist(r,@f))
function dC = f(a,b)
[m,~]=size(b);
for i=1:m
dC = sum(abs(a - b(i,:))./(abs(a) + abs(b(i,:))));
end
end

Accepted Answer

Andrei Bobrov
Andrei Bobrov on 2 Jul 2017
Edited: Andrei Bobrov on 2 Jul 2017
r = [0 3 4 5;7 6 3 -1;-1 1 -1 1;2 3 4 5];
for MATLAB >= R2016b
dist = squareform(pdist(r,@(a,b)sum(abs(a - b)./(abs(a) + abs(b)),2)))
for MATLAB <= R2016a
f = @(a,b)sum(abs(bsxfun(@minus,a,b))./bsxfun(@plus,abs(a),abs(b)),2);
dist1 = squareform(pdist(r,f))
for your code
dist = squareform(pdist(r,@f))
function dC = f2(a,b)
[m,~] = size(b);
dC = zeros(m,1);
for ii=1:m
dC(ii) = sum(abs(a - b(ii,:))./(abs(a) + abs(b(ii,:))));
end
end
  1 Comment
MByk
MByk on 2 Jul 2017
Thank you very much, it is working now. Much appreciated.

Sign in to comment.

More Answers (0)

Categories

Find more on Statistics and Machine Learning Toolbox in Help Center and File Exchange

Tags

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!