MATLAB Answers

MATLAB's custom distance function example for two matrices.

24 views (last 30 days)
hello_world
hello_world on 22 Jul 2018
Answered: Viren Gupta on 7 Aug 2018
How does MATLAB's @distfun work for two matrices. Suppose:
X1 = rand(5);
X2 = rand(3);
How to compute the KL-Divergence between X1 and X2 using @distfun? I do not see any non trivial distance example in manual. Please advise.
  2 Comments
hello_world
hello_world on 3 Aug 2018
@Viren Gupta: I also followed document and trivial example given there. Can you show me a working example for non trivial cases, such as, KL Divergence which depends on two probability distributions P and Q. So, you may generate two random distributions.

Sign in to comment.

Accepted Answer

Viren Gupta
Viren Gupta on 7 Aug 2018
Here is a working example if you want to find KL divergence between 2 vectors.
z1=rand(1,5);
z2=rand(1,5);
X=[z1;z2];
fn=@distfun;
d=pdist(X,fn);
function f = distfun(x1,x2)
l=size(x1,2);
KL=0;
for i=1:l
KL=KL+x2(i)*log(x2(i)/x1(i));
end
f=KL;
end
Hope this helps.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!