我想知道matlab的nansum
函数。
X = magic(3);
X([1 6:9]) = repmat(NaN, 1, 5);
X =
NaN 1 NaN
3 5 NaN
4 NaN NaN
然后致电
>> nansum(X, 1)
ans =
7 6 0
>> nansum(X, 2)
ans =
1
8
4
它按预期工作。
但是,我没想到的是它也适用于
>> nansum(X, 400)
ans =
0 1 0
3 5 0
4 0 0
这是什么原因?为什么不会因为dim
超出矩阵尺寸的错误而崩溃?
答案 0 :(得分:10)
在MATLAB中,所有数组/矩阵都具有无限的单例尾随维度。
单例维度是dim
,其中size(A,dim) = 1
。当它位于所有非单维度之后(即它不会改变矩阵的结构)时,称为尾随单维度。
任何可以在特定维度上运行的函数(包括nansum
)都可以在任何无限单例维度上进行操作。通常,您不会看到任何影响(例如,以这种方式使用max
或sum
只需返回输入 [1] ),但是nansum
会替换{{1 }}为零,这就是全部。
请注意,NaN
与nansum(A,dim)
相同。您可以通过键入sum(A,dim,'omitnan')
来查看。因此,我的示例为方便起见使用了edit nansum
。有关定义的行为的参考,请参见此答案的底部。
让我们尝试将其可视化:
sum
如果需要,您可以A = ones(3,4);
size( A ) % >> ans = [3, 4]
% Under the hood:
% size( A ) = [3, 4, 1, 1, 1, 1, ...]
sum( A, 1 ) % Sum through the rows, or the 1st dimension, which has 3 elements per sum
% >> ans = [3 3 3 3]
sum( A, 2 ) % Sum through the columns, or the 2nd dimension, which has 4 elements per sum
% >> ans = [4; 4; 4]
sum( A, 400 ) % Sum through the ???, the 400th dimension, which has 1 element per sum
% >> ans = [1 1 1 1; 1 1 1 1; 1 1 1 1]
使原始矩阵具有从2维到399维的单例来进一步实现这一点:
reshape
现在我们可以做一个类似的% Set up dimensions as [3, 1, 1, ..., 1, 1, 4], for a 400-D array!
dims = num2cell( [3 ones(1,398), 4] );
% Note we'll now still have trailing singleton dims, but have 398 in the structure too
B = reshape( A, dims{:} );
示例。最后要知道的是,sum
删除了非跟踪单例尺寸,我们可以使用它来整理输出:
squeeze
我们可以看到,现在我们已经进行了重塑,第400维的求和与第2维的原始求和相同,反之亦然。如果将3替换为400,这将更容易看到!
[ 1 ]请参见sum
和max
文档作为示例,其中明确定义了行为“如果dim大于sum( B, 1 ); % >> ans(:,:,1,1,1,...,1) = 3
% >> ans(:,:,1,1,1,...,2) = 3
% >> ans(:,:,1,1,1,...,3) = 3
% >> ans(:,:,1,1,1,...,4) = 3
squeeze( sum( B, 1 ) ); % >> ans = [3; 3; 3; 3]
% similarly
squeeze( sum( B, 2 ) ); % >> ans = [1 1 1 1; 1 1 1 1; 1 1 1 1]
squeeze( sum( B, 400 ) ); % >> ans = [4; 4; 4]
”。在这两种情况下,仅返回ndims(A)
都可以提高实现效率。对于A
,如果元素为nansum
,则必须进行一些计算。
答案 1 :(得分:2)
矩阵确实具有第400维。它是1。因此,当您对此维求和时,它只返回您作为输入给出的矩阵,其中NaN
s省略/计数为0。
与标准sum
>>A = magic(3)
A =
8 1 6
3 5 7
4 9 2
>>sum(A,400)
ans =
8 1 6
3 5 7
4 9 2
编辑:也许更好的例子是
A = 5;
此变量具有size(A)=[1,1];
,换句话说,维度1的大小与{400维度一样,为1
,但求和仍然有意义
sum(A)
ans =
5
答案 2 :(得分:2)
矩阵没有第400维(更好的是,它具有无限的隐式单例维),只是当dim输入超过矩阵维时,sum的实现会返回矩阵,如sum的文档所述:
sum在dim大于ndims(A)或size(A,dim)为1时返回A