Fanning Software Consulting

Adding Vectors Containing NANs

QUESTION: I have two vectors (vec1 and vec2). Some of the values of vec1 are set as NaN (not-a-number). I want to sum each point of vec1 with its correspondent point in vec2, ignoring NaN. For example, I define my vectors like this.

   vec1 = FltArr(5) + 1
   vec1[2] = !Values.F_NAN
   vec2 = FltArr(5) + 1
   Print, vec1
            1.00000      1.00000          NaN      1.00000      1.00000
   Print, vec2
            1.00000      1.00000      1.00000      1.00000      1.00000

If I try this:

   Print, new_vec
            2.00000      2.00000          NaN      2.00000      2.00000

I have NaN's in new_vec which correspond to the NANs in vec1.

If I use Total, IDL tells me that vec2 should be a scalar in this context.

   new_vec = Total(vec1, vec2, /NAN) 
      % TOTAL: Expression must be a scalar or 1 element array in this context: VEC2.
      % Execution halted at: $MAIN$   

Is there any other way to ignore the NaN's?

ANSWER: This answer is supplied by Klaus Scipal (

You were right to think of Total, but you are using it incorrectly. The correct syntax is like this.

   new_vec = [[vec1],[vec2]]
   new_vec = Total(new_vec, 2, /NAN)
   Print, new_vec
            2.00000      2.00000      1.00000      2.00000      2.00000

Web Coyote's Guide to IDL Programming