0001 function [x,mn]=nt_demean(x,w)
0002
0003
0004
0005
0006
0007
0008
0009
0010
0011 if nargin<2; w=[]; end
0012 if nargin<1; error('!');end
0013 nt_greetings;
0014
0015 if iscell(x)
0016 if ~isempty(w); error('!'); end;
0017 for iCell=1:numel(x)
0018 [x{iCell},mn{iCell}]=nt_demean(x{iCell});
0019 end
0020 return;
0021 end
0022
0023 if ~isempty(w) && numel(w)<size(x,1)
0024 w=w(:);
0025
0026 if min(w)<1 || max(w)>size(x,1);
0027 error('w interpreted as indices but values are out of range');
0028 end
0029 ww=zeros(size(x,1),1);
0030 ww(w)=1;
0031 w=ww;
0032 end
0033
0034
0035 if size(w,3)~=size(x,3);
0036 if size(w,3)==1 && size(x,3)~=1;
0037 w=repmat(w,[1,1,size(x,3)]);
0038 else
0039 error('W should have same npages as X, or else 1');
0040 end
0041 end
0042
0043 [m,n,o]=size(x);
0044 x=nt_unfold(x);
0045
0046 if isempty(w);
0047
0048 mn=mean(double(x),1);
0049 x=nt_vecadd(x,-mn);
0050
0051 else
0052
0053 w=nt_unfold(w);
0054
0055 if size(w,1)~=size(x,1)
0056 error('X and W should have same nrows');
0057 end
0058
0059
0060 if size(w,2)==1;
0061 mn=sum(nt_vecmult(double(x),w),1) ./ (sum(w,1)+eps);
0062 elseif size(w,2)==n;
0063 mn=sum(x.*w) ./ (sum(w,1)+eps);
0064 else
0065 error('W should have same ncols as X, or else 1');
0066 end
0067
0068
0069 x=nt_vecadd(x,-mn);
0070
0071 end
0072
0073 x=nt_fold(x,m);
0074