comparison _misc/probability/.svn/text-base/KLDiv.m.svn-base @ 8:b5b38998ef3b

added all that other stuff
author matthiasm
date Fri, 11 Apr 2014 15:54:25 +0100
parents
children
comparison
equal deleted inserted replaced
7:12abff5474c8 8:b5b38998ef3b
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
10
11
12 if size(P,2)~=size(Q,2)
13 error('the number of columns in P and Q should be the same');
14 end
15
16 if sum(~isfinite(P(:))) + sum(~isfinite(Q(:)))
17 error('the inputs contain non-finite values!')
18 end
19
20 % normalizing the P and Q
21 if size(Q,1)==1
22 Q = Q ./sum(Q);
23 P = P ./repmat(sum(P,2),[1 size(P,2)]);
24 dist = sum(P.*log(P./repmat(Q,[size(P,1) 1])),2);
25
26 elseif size(Q,1)==size(P,1)
27
28 Q = Q ./repmat(sum(Q,2),[1 size(Q,2)]);
29 P = P ./repmat(sum(P,2),[1 size(P,2)]);
30 dist = sum(P.*log(P./Q),2);
31 end
32
33 % resolving the case when P(i)==0
34 dist(isnan(dist))=0;
35