sum on empty arrays
5 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
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))
sum(zeros(1,0))
sum(zeros(2,0)) % This is returns an odd result, or not coherent with the second statement
sum(zeros(2,0),'all')
5 comentarios
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.
Respuesta aceptada
Steven Lord
el 10 de Feb. de 2022
sum(zeros(0,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
case3 = sum(zeros(2,0)) % Sums along first nonsingleton dimension, dimension 2
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
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
v2 = reshape(A, [], 1) % the transpose of case2
which when summed will give you the 1-by-1 value 0.
Más respuestas (0)
Ver también
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!