sum on empty arrays
古いコメントを表示
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 件のコメント
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.
(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
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
2022 年 2 月 10 日
採用された回答
その他の回答 (0 件)
カテゴリ
ヘルプ センター および File Exchange で Performance and Memory についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!