function f = zeromean(m,dim) <m> is a matrix <dim> (optional) is the dimension of interest. if supplied, subtract off the mean of each case oriented along <dim>. if [] or not supplied, subtract off the global mean. subtract off the mean of <m>, either of individual cases or the global mean. we use nanmean to deal with NaNs gracefully. note some weird cases: zeromean([]) is [] zeromean([NaN NaN]) is [NaN NaN] example: a = [1 1; 2 0]; isequal(zeromean(a),[0 0; 1 -1]) a = [1 NaN]; isequalwithequalnans(zeromean(a,1),[0 NaN])
0001 function f = zeromean(m,dim) 0002 0003 % function f = zeromean(m,dim) 0004 % 0005 % <m> is a matrix 0006 % <dim> (optional) is the dimension of interest. 0007 % if supplied, subtract off the mean of each case oriented along <dim>. 0008 % if [] or not supplied, subtract off the global mean. 0009 % 0010 % subtract off the mean of <m>, either of individual cases or the global mean. 0011 % we use nanmean to deal with NaNs gracefully. 0012 % 0013 % note some weird cases: 0014 % zeromean([]) is [] 0015 % zeromean([NaN NaN]) is [NaN NaN] 0016 % 0017 % example: 0018 % a = [1 1; 2 0]; 0019 % isequal(zeromean(a),[0 0; 1 -1]) 0020 % a = [1 NaN]; 0021 % isequalwithequalnans(zeromean(a,1),[0 NaN]) 0022 0023 % do it 0024 if ~exist('dim','var') || isempty(dim) 0025 f = m - nanmean(m(:)); 0026 else 0027 f = bsxfun(@minus,m,nanmean(m,dim)); 0028 end