MATLAB: Why is 1+ nan*1i = NaN + NaNi

complex numbersnan

Dear all,
I am trying to figure out how to store some information using complex numbers and retrieving that information later on.
For an operation like
1+nan*1i,
I would like to be able to retrieve "1" by doing
real(1+nan*1i)
and retrieve "nan" by doing
imag(1+nan*1i).
The first case does not work because matlab stores 1+ nan*1i as NaN + NaNi. Is there any workaround to this?
Thanks

Best Answer

I don't envision any workaround that would specifically make NaNs work. Speaking mathematically very loosely, the NaN in your original expression could be a "complex NaN", such that the NaN-ness leaks over to the real part.
I can imagine, without deep thinking, a couple workarounds, that are annoying in their own way, but might work in your particular situation.
  • Use another matrix dimension to keep real and imaginary parts separate
  • Define your own complex number object, that has the properties you outline above.