0001 function x=nt_demean(x,w)
0002
0003
0004
0005
0006
0007
0008
0009
0010
0011
0012
0013
0014
0015
0016 if nargin<2; w=[]; end
0017 if nargin<1; error('!');end
0018 nt_greetings;
0019
0020 if iscell(x)
0021 if isempty(w)
0022 for k=1:numel(x)
0023 x{k}=nt_demean(x{k});
0024 end
0025 else
0026 if ~iscell(w)||numel(w)~=numel(x); error('!'); end
0027 for k=1:numel(x)
0028 x{k}=nt_demean(x{k},w{k});
0029 end
0030 end
0031 return
0032 end
0033
0034 if isempty(w);
0035
0036 m=size(x,1);
0037 x=nt_unfold(x);
0038 mn=mean(double(x),1);
0039 x=bsxfun(@plus,x,-mn);
0040 x=nt_fold(x,m);
0041
0042 else
0043
0044 if numel(w)<size(x,1)
0045 w=w(:);
0046 if min(w)<1 || max(w)>size(x,1);
0047 error('w interpreted as indices but values are out of range');
0048 end
0049 ww=zeros(size(x,1),1);
0050 ww(w)=1;
0051 w=ww;
0052 end
0053
0054 if size(w,1)~=size(x,1)
0055 error('X and W should have same nrows');
0056 end
0057
0058 if ndims(x)==3
0059
0060 if size(w,3)==1
0061 w=repmat(w,[1,1,size(x,3)]);
0062 elseif size(w,3)~=size(x,3)
0063 error('W should have same npages as X, or else 1');
0064 end
0065 end
0066
0067
0068 x(:,max(w,1)==0)=0;
0069
0070
0071 m=size(x,1);
0072 x=nt_unfold(x);
0073 w=nt_unfold(w);
0074
0075 if size(w,2)==size(x,2);
0076 mn=(sum(x.*w) +eps) ./ (sum(w,1)+eps);
0077 elseif size(w,2)==1;
0078
0079 mn=(sum(bsxfun(@times, double(x),w),1)+eps) ./ (sum(w,1)+eps);
0080 else
0081 error('W should have same ncols as X, or else 1');
0082 end
0083
0084 x=bsxfun(@minus,x,mn);
0085 x=nt_fold(x,m);
0086 w=nt_fold(w,m);
0087 end
0088
0089 if nargout==0
0090 if ndims(x)==3; x=mean(x,3); w=max(w,[],3); end
0091 figure(1); clf;
0092 plot(x);
0093 if ~ isempty(w)
0094 hold on;
0095 if size(w)==size(x)
0096 x(find(~w))=nan;
0097 else
0098 x(find(~w),:)=nan;
0099 end
0100
0101 plot(x,'linewidth',2)
0102 end
0103 clear x;
0104 hold off
0105 end