sum on empty arrays
Mostrar comentarios más antiguos
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
a hint is to look at the type of objects. zeros(1,0) is a 'row vector' object, and its sum is a scalar operating along the only dimension. zeros(2,0) is a matrix object, so its sum operates across one of the two dimensions
i agree that its unexpected, but not counterintuitive looked at this way.
Bruno Luong
el 10 de Feb. de 2022
Editada: Bruno Luong
el 10 de Feb. de 2022
(someone more expert than myself can answer this, but i think matrices adn arrays in matlab may just be, at a very base level, 1dimensional with accounting to provide multidimenional represnetations).
i'll play devil's advocate, because i don't know the answer.
zeros(0,0) has neither rows nor columns initialized, so seems like it should be scalar; initialized as null in both dimensions, there are no 'axes' to sum over so you get a scalar zero.
However, that doesn't explain why the nd-array case sum(zeros(0,0,0)) does give you want you want: a 1x0x0 empty array. I suspect this has to do with special rules for how empty objects are initialized. This is an interesting question.
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
el 10 de Feb. de 2022
Respuesta aceptada
Más respuestas (0)
Categorías
Más información sobre Performance and Memory en Centro de ayuda y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!