User defined distance function

5 visualizzazioni (ultimi 30 giorni)
MByk
MByk il 2 Lug 2017
Commentato: MByk il 2 Lug 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

Risposta accettata

Andrei Bobrov
Andrei Bobrov il 2 Lug 2017
Modificato: Andrei Bobrov il 2 Lug 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 Commento
MByk
MByk il 2 Lug 2017
Thank you very much, it is working now. Much appreciated.

Accedi per commentare.

Più risposte (0)

Categorie

Scopri di più su Statistics and Machine Learning Toolbox in Help Center e File Exchange

Tag

Community Treasure Hunt

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

Start Hunting!

Translated by