NAN add works strange

1 view (last 30 days)
SQ
SQ on 2 Oct 2015
Commented: Steven Lord on 2 Oct 2015
Hi,
I got some question about Nan. As you can see in my code, NaN+1=Nan, but when I add two matrix value (one is Nan while the other one is -31),the sum is 0.
Could anyone help me out? I hope it could be either -31 or Nan (Or the best would be I can choose whether to get Nan or -31)
>> Temp_abs(1,1)
ans =
-31
>> mean(Temp_anomali(1,1,:))
ans =
NaN
>> mean(Temp_anomali(1,1,:))+Temp_abs(1,1)
ans =
0
>> nan+1
ans =
NaN
>> nan-31
ans =
NaN
Many thanks
PS. The Temp_anomali(1,1,:) are all Nan.
  2 Comments
Jon
Jon on 2 Oct 2015
Can you provide the values of Temp_anomali(1,1,:)?
Star Strider
Star Strider on 2 Oct 2015
What MATLAB version are you using? I cannot reproduce your results with this code in R2015b:
Temp_anomali(1,1,:) = [1:10 NaN 11:15];
Temp_abs(1,1) = -31;
Q1 = mean(Temp_anomali(1,1,:))
Q2 = mean(Temp_anomali(1,1,:))+Temp_abs(1,1)
Q1 =
NaN
Q2 =
NaN

Sign in to comment.

Accepted Answer

Steven Lord
Steven Lord on 2 Oct 2015
The class of Temp_abs is one of the four signed integer types (int8, int16, int32, or int64.) When you add a value of an integer type and a scalar double, the result is of the integer type. Since there are no bit patterns available to represent NaN in an integer type (all the bit patterns of the appropriate length are used in storing values between INTMIN and INTMAX for the class inclusive) the NaN gets converted into a zero of that integer class.
x = NaN;
y = int8(-32);
z = x+y
class(z)
You will see that z is 0 and its class is int8.
w = -32;
v = x+w
class(v)
You will see that v is NaN and its class is double, since double plus double results in a double.
  2 Comments
SQ
SQ on 2 Oct 2015
Edited: SQ on 2 Oct 2015
Thank you very much! This is the answer I need :)
Temp_abs is int 16 in my original document, which caused the problem!
I am just wondering, if it is possible to add Nan with a number, and the mean is the number?
For example, if Nan+3+5, mean =4
Thanks again!
Steven Lord
Steven Lord on 2 Oct 2015
Are you using release R2015a or later of MATLAB?
mean([NaN, 3, 5], 'omitnan')
If not, do you have Statistics and Machine Learning Toolbox (or Statistics Toolbox, if you have an older release?)
nanmean([NaN, 3, 5])

Sign in to comment.

More Answers (0)

Tags

Community Treasure Hunt

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

Start Hunting!