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