Matlab replaces missing doubles by zeros instead of NaNs
2 次查看(过去 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(4) = 4
s = ["a" "b"]
s(4) = "d"
0 个评论
回答(1 个)
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.
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!