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