What is the reasoning behind the fact that min(0,NaN) is 0?
16 views (last 30 days)
Show older comments
the cyclist on 21 May 2012
Answered: Mark vanRossum on 3 Jun 2021
I know that Mathworks pays a lot of attention to this stuff, so I am wondering why the expression
is 0. Returning a NaN here seems more logical to me.
Stephen23 on 25 Apr 2020
Edited: Stephen23 on 26 Apr 2020
@Bryan: you should make that as an enhancement request.
Another option is to stop relying on inconsistent "default" behavior and always specify any flags, dimensions, etc. for any function that has these kind of options. Although it requires a little more typing, it has the following advantages:
- makes the intention clear
- avoids bugs, e.g. when a matrix ony has one row (and thus min returns a scalar, not a row vector)
- throws an error on versions that do not support that option, rather than silently continuing...
Walter Roberson on 21 May 2012
If you initialize the result to inf, and then loop testing whether the current value is less than the result and replace the result if it is, then since NaN < any number is false, the result will never get replaced with NaN. You would have to add special code to return NaN in such a case.
Sean de Wolski on 21 May 2012
Jan on 22 May 2012
It depends on how you understand the MIN function. 0 < NaN replies FALSE, but NaN < 0 replies FALSE also. As long as it is well documented, both values are reasonable.
Daniel Shub on 22 May 2012
Given the behavior of MIN, I find it odd that there is a NANMIN function.
per isakson on 21 Jun 2012
MIN and MAX ignores NaN. MEAN and SUM does not. I guess NANMIN (in stat toolbox) is for people like me who cannot remember all the details when we cannot see the underlying logic.
M Sohrabinia on 21 Jun 2012
NaN is considered undefined, so undefined is ignored by most functions (0/0 will be resulted in NaN which is basically undefined but any number divided by 0, say 4/0, will result in inf). However, the question is why Matlab has decided to treat NaNs in a certain way in some functions, e.g., sort function will always arrange NaNs at the top end (A to Z mode). I guess Matlab has just decided to adopt some rules to handle exceptions.
Mark vanRossum on 3 Jun 2021
I encountered this when working on arrays.
x=[1 NaN 10];
y=[5 5 5];
m=min(x,y) and m=nanmin(x,y) return [1,5,5]
In V2020, min(x,y,'includenan') returns [1, NaN,5]
Here is an ugly workaround to get the desired behaviour in older versions.
Find more on NaNs in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!Start Hunting!