function y = nan_std(x)
% NAN_STD - return the standard deviation ignoring NaNs
%

% 
%	$Revision: 1.4 $
%	$Date: 2008/02/18 19:37:23 $
%	$Id: nan_std.m,v 1.4 2008/02/18 19:37:23 duncombe Exp duncombe $
% 
% COMMENTS - There is a matlab function nanstd which does this
% 

nans = isnan(x);
i = find(nans);

% Find mean
avg = nan_mean(x);

if min(size(x))==1,
   count = length(x)-sum(nans);
   x = x - avg;
else
   count = size(x,1)-sum(nans);
   x = x - avg(ones(size(x,1),1),:);
end

% Replace NaNs with zeros.
x(i) = zeros(size(i));

% Protect against a column of all NaNs
i = find(count==0);
count(i) = ones(size(i));
y = sqrt(sum(x.*x)./max(count-1,1));
y(i) = i + NaN;

