sum on empty arrays

5 ビュー (過去 30 日間)
Bruno Luong
Bruno Luong 2022 年 2 月 10 日
コメント済み: Bruno Luong 2022 年 2 月 10 日
Can someone explain the logic of third statement (Run under R2021b) :
sum(zeros(0,0))
ans = 0
sum(zeros(1,0))
ans = 0
sum(zeros(2,0)) % This is returns an odd result, or not coherent with the second statement
ans = 1×0 empty double row vector
sum(zeros(2,0),'all')
ans = 0
  5 件のコメント
AndresVar
AndresVar 2022 年 2 月 10 日
It's weird but kinda helpful in some cases. Since you usually want to sum a nonempty matrix, this way your result tells you it was empty and not just 0. So actually it would be nice if the other cases resulted in empty array rather than 0.
Bruno Luong
Bruno Luong 2022 年 2 月 10 日
I accept Steve's answer but surely jessupj comment is also spot on. Thanks.

サインインしてコメントする。

採用された回答

Steven Lord
Steven Lord 2022 年 2 月 10 日
sum(zeros(0,0))
ans = 0
This is a special case, see the definition of the input argument A on the documentation page for the sum function.
case2 = sum(zeros(1,0)) % Sums along first nonsingleton dimension, dimension 2
case2 = 0
case3 = sum(zeros(2,0)) % Sums along first nonsingleton dimension, dimension 2
case3 = 1×0 empty double row vector
If the dimension is not specified (as in case2 and case3) we sum along the first dimension whose size is not 1. The sizes of the result and A will be the same except that the size of the result in the first nonsingleton dimension of A is 1. In case2 the size of A is [1 0] and so the size of the result is [1 1]. In case3 the size of A is [2 0] and so the size of the result is [1 0].
sum(zeros(2,0),'all') % Sums along all dimensions, first dimension 1 then dimension 2
ans = 0
You can think of this as equivalent to reshaping the input into a vector then summing that vector. If you make zeros(2, 0) a vector what size is it?
A = zeros(2, 0);
v1 = reshape(A, 1, []) % case2 or
v1 = 1×0 empty double row vector
v2 = reshape(A, [], 1) % the transpose of case2
v2 = 0×1 empty double column vector
which when summed will give you the 1-by-1 value 0.
  1 件のコメント
Bruno Luong
Bruno Luong 2022 年 2 月 10 日
"This (BLU note: zeros(0,0) or []) is a special case, see the definition of the input argument A on the documentation page for the sum function."
Thanks, this is what we come up and I want to point out from the discussion.
It's quite odd that we use very often
sum([])
it's very convient to get 0, but without questioning the exeptional rule that leads to such result.
MATLAB is sometime tricky to correctly deal with.

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangePerformance and Memory についてさらに検索

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by