Matlab replaces missing doubles by zeros instead of NaNs
1 view (last 30 days)
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(4) = 4
s = ["a" "b"]
s(4) = "d"
dpb on 12 Aug 2022
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.