views:

128

answers:

2

I would like to do element wise addition over matrices while skipping NaN values. MATLAB and Octave have nansum, but it does column wise addition within a matrix.

Let:

a = NaN * zeros(3)
b = ones(3)


I want:

c = nan+(a, b)

and

c = b


and:

d = nan+(a,a)

and

d = a
+1  A: 
a_fixed = a;
a_fixed(isnan(a)) = 0;
b_fixed = b;
b_fixed(isnan(b)) = 0;
c = a_fixed.+b_fixed;
Ofri Raviv
Thanks, this is how i would have gone about it eventually, but its good to know how to use the cat and nansum method above also.
Naveen
+4  A: 

You can still use nansum, if you catenate your n-d arrays along the n+1st dimension.

For 2D

% commands de-nested for readability. You can do this with a single line, of course
tmp = cat(3,a,b);
c = nansum(tmp,3);

The general case

function out = nansumByElement(A,B)
%NANSUMBYELEMENT performs an element-wise nansum on the n-D arrays A and B
% A and B have to have the same size

% test input
if nargin < 2 || isempty(A) || isempty(B) || ndims(A)~=ndims(B) || ~all(size(A)==size(B))
error('please pass two non-empty arrays of the same size to nansumByElement')
end

% calculate output

nd = ndims(A); % get number of dimensions
% catenate and sum along n+1st dimension
out = nansum(cat(nd+1,A,B),nd+1);
Jonas
+1, I was about to post the same solution..
Amro
Thanks, that almost does it. <br>I still wanted NaN + NaN = NaN and not 0. <br>but, even nansum doesn't do that.
Naveen
I just addedout(and(isnan(A), isnan(B))) = NaNand now it works
Naveen

related questions