Home > NoiseTools > nt_wmean.m

# nt_wmean

## PURPOSE

y=nt_wmean(x,w,dim) - weighted average

## SYNOPSIS

function y=nt_wmean(x,w,dim)

## DESCRIPTION

    y=nt_wmean(x,w,dim) - weighted average

     y: vector of weighed means

     x: column vector or matrix of values to average columnwise
     w: column vector or matrix of weights (default: all ones)
     dim: dimension over which to average (default: 1)

     if x contains nans the corresponding weights are set to zero

## CROSS-REFERENCE INFORMATION

This function calls:

This function is called by:

- nt_bsmean [mn,sd,all]=nt_bsmean(x,N,w) - calculate mean, estimate sd using bootstrap
- nt_bsrms [rms,sd,all]=nt_bsrms(x,N,w) - calculate rms, estimate sd using bootstrap
- nt_dss1 [todss,pwr0,pwr1]=nt_dss1(x,w,keep1,keep2) - evoked-biased DSS denoising

## SOURCE CODE

    0001 function y=nt_wmean(x,w,dim)
    0002 %y=nt_wmean(x,w,dim) - weighted average
    0003 %
    0004 % y: vector of weighed means
    0005 %
    0006 % x: column vector or matrix of values to average columnwise
    0007 % w: column vector or matrix of weights (default: all ones)
    0008 % dim: dimension over which to average (default: 1)
    0009 %
    0010 % if x contains nans the corresponding weights are set to zero
    0011
    0012 if nargin<3; dim=[]; end
    0013 if nargin<2; w=[]; end
    0014
    0015 % treat nans as zero-weighted 0s
    0016 if numel(find(isnan(x)))>0
    0017     x(find(isnan(x)))=0;
    0018     if isempty(w)
    0019         w=ones(size(x));
    0020     end
    0021     w(find(isnan(x)))=0;
    0022 end
    0023
    0024 if isempty(dim); dim=1; end
    0025 if isempty(w)
    0026     y=mean(x,dim);
    0027 else
    0028     if size(x,1) ~= size(w,1); error('data and weight must have same nrows'); end
    0029     if size(w,2)==1; w=repmat(w,1,size(x,2)); end
    0030     if size(w,2) ~= size(x,2); error('weight must have same ncols as data, or 1'); end
    0031     y=sum(x.*w,dim)./sum(w,dim);
    0032     y(find(isnan(y)))=0;
    0033 end
    0034