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 x=nt_vecadd(x,-mn);
0035 x=nt_fold(x,m);
0036
0037 else
0038
0039 if numel(w)<size(x,1)
0040 w=w(:);
0041 if min(w)<1 || max(w)>size(x,1);
0042 error('w interpreted as indices but values are out of range');
0043 end
0044 ww=zeros(size(x,1),1);
0045 ww(w)=1;
0046 w=ww;
0047 end
0048
0049 if size(w,1)~=size(x,1)
0050 error('X and W should have same nrows');
0051 end
0052
0053 if ndims(x)==3
0054 if size(w,3)==1
0055 w=repmat(w,[1,1,size(x,3)]);
0056 elseif size(w,3)~=size(x,3)
0057 error('W should have same npages as X, or else 1');
0058 end
0059 end
0060
0061 m=size(x,1);
0062 x=nt_unfold(x);
0063 w=nt_unfold(w);
0064
0065 if size(w,2)==size(x,2);
0066 mn=sum(x.*w) ./ (sum(w,1)+eps);
0067 elseif size(w,2)==1;
0068 mn=sum(nt_vecmult(double(x),w),1) ./ (sum(w,1)+eps);
0069 else
0070 error('W should have same ncols as X, or else 1');
0071 end
0072
0073 x=bsxfun(@minus,x,mn);
0074 x=nt_fold(x,m);
0075 end
0076