sum2.m 459 Bytes
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
function y=sum2(x,dim)
%SUM2    Sum of elements. Ignores NaNs

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

if dim == 1
   nc=prod(dimx(2:end));
   xp=reshape(x,dimx(1),nc);
   y=zeros(1,size(xp,2));
   for j=1:nc
      y(j)=sum(xp(isfinite(xp(:,j)),j),1);
   end
   dimx(1)=1;
   y=reshape(y,dimx);
else
   perm=1:ndims(x); perm(dim)=[]; perm=[dim perm];
   y=ipermute(sum2(permute(x,perm),1),perm);
end