sum on empty arrays

5 visualizaciones (últimos 30 días)
Bruno Luong
Bruno Luong el 10 de Feb. de 2022
Comentada: Bruno Luong el 10 de Feb. de 2022
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 comentarios
AndresVar
AndresVar el 10 de Feb. de 2022
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 el 10 de Feb. de 2022
I accept Steve's answer but surely jessupj comment is also spot on. Thanks.

Iniciar sesión para comentar.

Respuesta aceptada

Steven Lord
Steven Lord el 10 de Feb. de 2022
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 comentario
Bruno Luong
Bruno Luong el 10 de Feb. de 2022
"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.

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Performance and Memory en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by