function y = nmean(x,dim)
%NMEAN  Average or mean value, ignoring NaN.
%   Same as MEAN, but NaN's are ignored.
%
% uses :	intvers.m

%   Copyright (c) 1997 by Toby Driscoll.
%   Adapted from MEAN.M, written by The MathWorks, Inc.
%   added backwards compatibility	G.Krahmann, LODYC Paris

if prod(size(x))==1, y = x; return, end

if nargin==1, 
  dim = min(find(size(x)~=1));
  if isempty(dim), dim = 1; end
end

if intvers>4
  mask = isnan(x);
  x(mask) = 0;
  s = sum(~mask,dim);
  s(s==0) = NaN;
  if ~isempty(x),
    y = sum(x,dim)./s;
  else
    y = NaN;
  end
else
  [m,n] = size(x);
  y = zeros(m,n);
  valid = ~isnan(x);
  y(valid) = x(valid);
  mi = sum(valid);
  if ~isempty(x)
    y = sum(y) ./ mi;
  else
    y = NaN;
  end
end
