Matlab replaces missing doubles by zeros instead of NaNs

2 Ansichten (letzte 30 Tage)
Benjamin Gaudin
Benjamin Gaudin am 12 Aug. 2022
Beantwortet: dpb am 12 Aug. 2022
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"

Antworten (1)

dpb
dpb am 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.

Kategorien

Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by