用NaN加2x2矩阵 [英] Adding 2x2 matrix with NaNs
问题描述
除了寻求编程建议外,MATLAB的一般性问题还不多-如果我有:
More of a general MATLAB question than looking for programming advice -- if I have:
y = cellfun(@(x)sum(x(:)), Z, 'un', 0);
其中每个单元格矩阵中都有NaN
和实数的组合,当我对每个单元格中这些矩阵的所有元素求和时,我总会得到total = NaN
,因为存在NaN
在那儿,否则它们将被忽略而只是对实数求和.我问的原因是因为我越来越:
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
所以我希望y
的第一个元素是:
so I would expect the first element of y
to be:
y{1,1} = 44
我怎么不知道这个?
推荐答案
要忽略NaN,只需在您的匿名函数中使用矢量索引,方法是替换冒号(:
)
与~isnan(x)
:
To ignore the NaNs, just use vector indexing in your anonymous function, by replacing the colon (:
)
with ~isnan(x)
:
@(x)sum(x(~isnan(x)))
所以您得到:
y = cellfun(@(x)sum(x(~isnan(x))), Z, 'un', 0);
这篇关于用NaN加2x2矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!