annotate toolboxes/FullBNT-1.0.7/KPMtools/logsumexp.m @ 0:cc4b1211e677 tip

initial commit to HG from Changeset: 646 (e263d8a21543) added further path and more save "camirversion.m"
author Daniel Wolff
date Fri, 19 Aug 2016 13:07:06 +0200
parents
children
rev   line source
Daniel@0 1 function s = logsumexp(a, dim)
Daniel@0 2 % Returns log(sum(exp(a),dim)) while avoiding numerical underflow.
Daniel@0 3 % Default is dim = 1 (rows) or dim=2 for a row vector
Daniel@0 4 % logsumexp(a, 2) will sum across columns instead of rows
Daniel@0 5
Daniel@0 6 % Written by Tom Minka, modified by Kevin Murphy
Daniel@0 7
Daniel@0 8 if nargin < 2
Daniel@0 9 dim = 1;
Daniel@0 10 if ndims(a) <= 2 & size(a,1)==1
Daniel@0 11 dim = 2;
Daniel@0 12 end
Daniel@0 13 end
Daniel@0 14
Daniel@0 15 % subtract the largest in each column
Daniel@0 16 [y, i] = max(a,[],dim);
Daniel@0 17 dims = ones(1,ndims(a));
Daniel@0 18 dims(dim) = size(a,dim);
Daniel@0 19 a = a - repmat(y, dims);
Daniel@0 20 s = y + log(sum(exp(a),dim));
Daniel@0 21 %i = find(~finite(y));
Daniel@0 22 %if ~isempty(i)
Daniel@0 23 % s(i) = y(i);
Daniel@0 24 %end