Adding 2x2 matrix with NaNs

限于喜欢 提交于 2019-12-10 21:09:45

问题


More of a general MATLAB question than looking for programming advice -- if I have:

y = cellfun(@(x)sum(x(:)), Z, 'un', 0);

where there are a combinations of NaN's and real numbers in each cell matrix, when I sum all elements of those matrices per cell, will I always get total = NaN because there are NaN's in there, or will they be ignored and just sum the real numbers. The reason I ask is because I am getting:

y = [NaN] [NaN] [NaN]
    [NaN] [NaN] [NaN]
    [NaN] [NaN] [NaN]

an example cell matrix (cell element) would be:

x{1,1} = NaN 2   3
         4   5   6
         7   8   9

so I would expect the first element of y to be:

y{1,1} = 44

How am I not getting this?


回答1:


To ignore the NaNs, just use vector indexing in your anonymous function, by replacing the colon (:)
with ~isnan(x):

@(x)sum(x(~isnan(x)))

So you get:

y = cellfun(@(x)sum(x(~isnan(x))), Z, 'un', 0);



回答2:


You should use nansum (from the Statistics toolbox) rather than sum.

If you don't have the Statistics toolbox, then you can define nansum easily by:

function x = nansum(array,dim)

if nargin < 2
    if size(array,1) == 1
        dim = 2;
    else
        dim = 1;
    end
end

array(isnan(array)) = 0;

x  = sum(array,dim);

Essentially, the issue is that sum tried to sum every element of the input vector. If one of those elements is NaN then the entire sum is NaN (you can think of NaN as representing unknown data - obviously if you don't know what one of the pieces of data is, then you can't know what the sum of all pieces of data is either).

The function nansum treats all missing data as zero, so the following code gives the result you expect:

>> nansum( [NaN 2 3 4 5 6 7 8 9] )
ans =
    44



回答3:


If you don't have statistics toolbox, you should use ignoreNan from the file exchange.

   ignoreNan(array,@sum,dim)

In your case, you should reshape the matrix first:

   ignoreNan(x(:),@sum);

It is also more generic than nansum, in the sense that it can be used for any function - whether custom or built-in.



来源:https://stackoverflow.com/questions/11292462/adding-2x2-matrix-with-nans

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!