matthiasm@8: function [M, z] = normalise(A, dim) matthiasm@8: % NORMALISE Make the entries of a (multidimensional) array sum to 1 matthiasm@8: % [M, c] = normalise(A) matthiasm@8: % c is the normalizing constant matthiasm@8: % matthiasm@8: % [M, c] = normalise(A, dim) matthiasm@8: % If dim is specified, we normalise the specified dimension only, matthiasm@8: % otherwise we normalise the whole array. matthiasm@8: matthiasm@8: if nargin < 2 matthiasm@8: z = sum(A(:)); matthiasm@8: % Set any zeros to one before dividing matthiasm@8: % This is valid, since c=0 => all i. A(i)=0 => the answer should be 0/1=0 matthiasm@8: s = z + (z==0); matthiasm@8: M = A / s; matthiasm@8: elseif dim==1 % normalize each column matthiasm@8: z = sum(A); matthiasm@8: s = z + (z==0); matthiasm@8: %M = A ./ (d'*ones(1,size(A,1)))'; matthiasm@8: M = A ./ repmatC(s, size(A,1), 1); matthiasm@8: else matthiasm@8: % Keith Battocchi - v. slow because of repmat matthiasm@8: z=sum(A,dim); matthiasm@8: s = z + (z==0); matthiasm@8: L=size(A,dim); matthiasm@8: d=length(size(A)); matthiasm@8: v=ones(d,1); matthiasm@8: v(dim)=L; matthiasm@8: %c=repmat(s,v); matthiasm@8: c=repmat(s,v'); matthiasm@8: M=A./c; matthiasm@8: end matthiasm@8: matthiasm@8: