function c = addnan(a,b)
%ADDNAN   Add together two matrices ignoring elements equal to NaN.
%         c=addnan(a,b) has elements a(i,j)+b(i,j).   If a(i,j)
%         equals NaN, then c(i,j)=b(i,j).  If b(i,j) equals NaN, then
%         c(i,j)=a(i,j).  If a(i,j) and b(i,j) both equal NaN, then
%         c(i,j)=NaN.
% 
%         See also AVGNAN, CORNAN, MAXNAN, MINNAN, SUMNAN.

%         Ellen R. McGrattan, 2-6-97
%         Revised, 7-7-97, ERM

[l,m]  = size(a);
[n,p]  = size(b);
if l~=n | m~=p;
  error('a and b must have the same dimensions')
  return
end;

A      = zeros(l,m);
B      = A;
C      = A;
c      = NaN*ones(l,m);

na     = find(~isnan(a));
nb     = find(~isnan(b));
nc     = find(isnan(a) & isnan(b));

A(na)  = a(na);
B(nb)  = b(nb);
C(nc)  = c(nc);

c      = A+B+C;
