why am i getting complex values when I should be getting reals?

10 views (last 30 days)
I was doing some statistics for model performance where I was looping through large arrays with many NaN values. While performing log(value) in the loop matlab spit out complex numbers for a short spurt for no apparent reason. All the values should have been real or NaN and it was giving me NaN+NaNi or complex values of reals such as 0.0013+0.0004i. It did this for two arrays only and only for short bursts and then went back to behaving. Does anyone know why this occurs? or how to stop it from happening? Thank you.
  2 Comments
jgg
jgg on 28 Jan 2016
Edited: jgg on 28 Jan 2016
Are you sure there were no negative values in your loop? Log will return complex values if there are negative terms.
Andre
Andre on 28 Jan 2016
Edited: Andre on 28 Jan 2016
There is one but this behavior starts some 30 values prior to that and on a NaN. When I remove the negative number it stops but it still is odd to me that the complex numbers appear before they should.

Sign in to comment.

Answers (1)

Star Strider
Star Strider on 28 Jan 2016
The log of negative values will be complex. The ‘NaN + NaNi’ values are due to the vector (or array) being complex for other values.
You can prevent the complex values by taking log(abs(x)). You have to decide if that is correct for your code.
  1 Comment
Star Strider
Star Strider on 28 Jan 2016
We need to see your code.
How do you get from ‘A’ to ‘B’? If I understand your Comment correctly, ‘A’ has 3422 elements, so you’re doing something other than reshaping it to get ‘B’.

Sign in to comment.

Categories

Find more on Creating and Concatenating Matrices in Help Center and File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!