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