annotate toolboxes/FullBNT-1.0.7/KPMstats/gaussian_prob.m @ 0:e9a9cd732c1e tip

first hg version after svn
author wolffd
date Tue, 10 Feb 2015 15:05:51 +0000
parents
children
rev   line source
wolffd@0 1 function p = gaussian_prob(x, m, C, use_log)
wolffd@0 2 % GAUSSIAN_PROB Evaluate a multivariate Gaussian density.
wolffd@0 3 % p = gaussian_prob(X, m, C)
wolffd@0 4 % p(i) = N(X(:,i), m, C) where C = covariance matrix and each COLUMN of x is a datavector
wolffd@0 5
wolffd@0 6 % p = gaussian_prob(X, m, C, 1) returns log N(X(:,i), m, C) (to prevents underflow).
wolffd@0 7 %
wolffd@0 8 % If X has size dxN, then p has size Nx1, where N = number of examples
wolffd@0 9
wolffd@0 10 if nargin < 4, use_log = 0; end
wolffd@0 11
wolffd@0 12 if length(m)==1 % scalar
wolffd@0 13 x = x(:)';
wolffd@0 14 end
wolffd@0 15 [d N] = size(x);
wolffd@0 16 %assert(length(m)==d); % slow
wolffd@0 17 m = m(:);
wolffd@0 18 M = m*ones(1,N); % replicate the mean across columns
wolffd@0 19 denom = (2*pi)^(d/2)*sqrt(abs(det(C)));
wolffd@0 20 mahal = sum(((x-M)'*inv(C)).*(x-M)',2); % Chris Bregler's trick
wolffd@0 21 if any(mahal<0)
wolffd@0 22 warning('mahal < 0 => C is not psd')
wolffd@0 23 end
wolffd@0 24 if use_log
wolffd@0 25 p = -0.5*mahal - log(denom);
wolffd@0 26 else
wolffd@0 27 p = exp(-0.5*mahal) / (denom+eps);
wolffd@0 28 end