Matlab replaces missing doubles by zeros instead of NaNs

1 次查看(过去 30 天)
Matlab replaces doubles that are not set by zeros instead of NaNs (=double(missing)), with no error nor warning. This is a dangerous feature, any reason why?
Strings handle the case as expected, by inserting a <missing> (=string(missing)).
d = [1 2]
d = 1×2
1 2
d(4) = 4
d = 1×4
1 2 0 4
s = ["a" "b"]
s = 1×2 string array
"a" "b"
s(4) = "d"
s = 1×4 string array
"a" "b" <missing> "d"

回答(1 个)

dpb
dpb 2022-8-12
The "WHY" goes back to original design of MATLAB and was the chosen behavior when first invented.
To change that behavior now would be unthinkable in the effect it would have on existing code.
I can't think of any time this has ever "bit" in a practical sense or application; of course one knows of it as default behavior and so it becomes expected behavior with experience and to know to program defensively if there ever is a situation in which it could be needed to treat differently.
Preallocation with nan instead would be the most straightforward way although not always convenient to know a priori what size will be.
I will note that personally I definitely try very hard to avoid such a use case as you illustrate from happening -- that is adding a reference outside an array, unless it is simply for allocation since the syntax
clear x % ensure x isn't in memory first
x(100,2)=0; % equivalent to x=zeros(100,2);
is a fairly common MATLAB idiom for experienced users.

Community Treasure Hunt

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

Start Hunting!

Translated by