annotate _misc/probability/.svn/text-base/KLDiv.m.svn-base @ 9:4ea6619cb3f5 tip

removed log files
author matthiasm
date Fri, 11 Apr 2014 15:55:11 +0100
parents b5b38998ef3b
children
rev   line source
matthiasm@8 1 function dist=KLDiv(P,Q)
matthiasm@8 2 % dist = KLDiv(P,Q) Kullback-Leibler divergence of two discrete probability
matthiasm@8 3 % distributions
matthiasm@8 4 % P and Q are automatically normalised to have the sum of one on rows
matthiasm@8 5 % have the length of one at each
matthiasm@8 6 % P = n x nbins
matthiasm@8 7 % Q = 1 x nbins or n x nbins(one to one)
matthiasm@8 8 % dist = n x 1
matthiasm@8 9
matthiasm@8 10
matthiasm@8 11
matthiasm@8 12 if size(P,2)~=size(Q,2)
matthiasm@8 13 error('the number of columns in P and Q should be the same');
matthiasm@8 14 end
matthiasm@8 15
matthiasm@8 16 if sum(~isfinite(P(:))) + sum(~isfinite(Q(:)))
matthiasm@8 17 error('the inputs contain non-finite values!')
matthiasm@8 18 end
matthiasm@8 19
matthiasm@8 20 % normalizing the P and Q
matthiasm@8 21 if size(Q,1)==1
matthiasm@8 22 Q = Q ./sum(Q);
matthiasm@8 23 P = P ./repmat(sum(P,2),[1 size(P,2)]);
matthiasm@8 24 dist = sum(P.*log(P./repmat(Q,[size(P,1) 1])),2);
matthiasm@8 25
matthiasm@8 26 elseif size(Q,1)==size(P,1)
matthiasm@8 27
matthiasm@8 28 Q = Q ./repmat(sum(Q,2),[1 size(Q,2)]);
matthiasm@8 29 P = P ./repmat(sum(P,2),[1 size(P,2)]);
matthiasm@8 30 dist = sum(P.*log(P./Q),2);
matthiasm@8 31 end
matthiasm@8 32
matthiasm@8 33 % resolving the case when P(i)==0
matthiasm@8 34 dist(isnan(dist))=0;
matthiasm@8 35