function y=nt_wmean(x,w,dim) 
%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

if nargin<3; dim=[]; end
if nargin<2; w=[]; end

% treat nans as zero-weighted 0s
if numel(find(isnan(x)))>0
    x(find(isnan(x)))=0;
    if isempty(w)
        w=ones(size(x));
    end
    w(find(isnan(x)))=0;
end

if isempty(dim); dim=1; end
if isempty(w)
    y=mean(x,dim);
else
    if size(x,1) ~= size(w,1); error('data and weight must have same nrows'); end
    if size(w,2)==1; w=repmat(w,1,size(x,2)); end
    if size(w,2) ~= size(x,2); error('weight must have same ncols as data, or 1'); end
    y=sum(x.*w,dim)./sum(w,dim);
    y(find(isnan(y)))=0;
end

