KLDiv.m 1.0 KB

123456789101112131415161718192021222324252627282930313233343536
  1. function dist=KLDiv(P,Q)
  2. % dist = KLDiv(P,Q) Kullback-Leibler divergence of two discrete probability
  3. % distributions
  4. % P and Q are automatically normalised to have the sum of one on rows
  5. % have the length of one at each
  6. % P = n x nbins
  7. % Q = 1 x nbins or n x nbins(one to one)
  8. % dist = n x 1
  9. % https://cn.mathworks.com/matlabcentral/fileexchange/20688-kullback-leibler-divergence
  10. if size(P,2)~=size(Q,2)
  11. error('the number of columns in P and Q should be the same');
  12. end
  13. if sum(~isfinite(P(:))) + sum(~isfinite(Q(:)))
  14. error('the inputs contain non-finite values!')
  15. end
  16. % normalizing the P and Q
  17. if size(Q,1)==1
  18. Q = Q ./sum(Q);
  19. P = P ./repmat(sum(P,2),[1 size(P,2)]);
  20. temp = P.*log(P./repmat(Q,[size(P,1) 1]));
  21. temp(isnan(temp))=0;% resolving the case when P(i)==0
  22. dist = sum(temp,2);
  23. elseif size(Q,1)==size(P,1)
  24. Q = Q ./repmat(sum(Q,2),[1 size(Q,2)]);
  25. P = P ./repmat(sum(P,2),[1 size(P,2)]);
  26. temp = P.*log(P./Q);
  27. temp(isnan(temp))=0; % resolving the case when P(i)==0
  28. dist = sum(temp,2);
  29. end