# Cumtrapz for matrix including NaN values

44 views (last 30 days)
Anna S on 15 Apr 2019
Commented: Anna S on 15 Apr 2019
I want to integrate a data field which sometimes also contains Nan values. The integration with cumtrapz then always is NaN as well, of course.
Is there a function (as for example nanmean instead of mean) which ignores NaN?
SALT = [ NaN NaN NaN NaN
NaN NaN NaN NaN
31.7313 NaN NaN NaN
31.9400 31.6944 NaN NaN
32.1753 31.9462 NaN NaN
32.2596 32.0371 31.7931 NaN
32.3248 32.2337 32.0498 NaN]
Q= cumtrapz(SALT)

Bjorn Gustavsson on 15 Apr 2019
Well, I think that in addition to calculating a cummulative integration you also should/need to extract the limits over which you have non-nan values, something like this:
for i2 = 1:size(SALT,2)
i1 = find(isfinite(SALT(:,i2)));
if ~isempty(i1)
I_OK(:,i2) = [i1(1) i1(end)];
CTS{i2} = cumtrapz(SALT(i1,i2));
end
end
In addition you should only use cumtrapz over contiguous regions with finite values, so my example works for the data you gave. You might(should) make sure that the indices i1 are without gaps/or take care of the cases where there are gaps.
HTH

#### 1 Comment

Anna S on 15 Apr 2019
Thanks, that's what I was searching for!