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