Best way to get rid of/ prevent function from creating complex numbers?

83 views (last 30 days)
I have a function called dfaedit which somehow sometimes gives me complex numbers as outputs. I have not found a good way to deal with this except for deleting the complex numbers all together. My online search didn't yield any useful results.
What is the best way to approach this? I would like to keep all the information in my data and prevent the function from creating complex numbers.
The code I am running is:
for k=1:length(nonglitch_xyz_h_ref)
Stephen23 on 2 Mar 2022
Edited: Stephen23 on 2 Mar 2022
"Does throwing away the imaginary part change its value? "
Yes: its value includes both the real and imaginary parts, so when you take only the real part you are "changing" its value.
"What is the best way to approach this?"
Find out why your code returns complex values.

Sign in to comment.

Answers (3)

John D'Errico
John D'Errico on 1 Mar 2022
Edited: John D'Errico on 1 Mar 2022
You cannot simply force that a complex number will never arise. There is no flag you can just set to tell MATLAB to never create a complex number. For example, what if you have a square root in your computations, and the argument just happens to be negative?
Can you write code that is more robust against this happening? Well, yes. But that requires you write careful, high quality code. It will require you to know what operations can create a complex result, and how to deal with that eventuality. Just part of being a good programmer.

David Goodmanson
David Goodmanson on 2 Mar 2022
Edited: David Goodmanson on 2 Mar 2022
Hello Jeffrey,
Deleting unsatisfactory results is of course not a good way to deal with this. I ran case {15} from your matfile data. In this case log_Q has 49 elements from 49 iterations. The first two entries are complex, the rest are real. We have
log_Q = log10(sqrt(s/den))
and the culprit is s, whose value is accumulated in a for loop for each of the 49 iterations. The first two iteration values are negative, the other 47 are positive, hence the complex result. So now you get to go back and find out why the first two s values come out negative. There might be an error, or maybe you will decide that the algorithm does not really apply in the first couple of iterations for reason such-and-such and eliminate those values, which is far better than deleting them ex post facto.

Akira Agata
Akira Agata on 1 Mar 2022
How about using isreal function?


Find more on Resizing and Reshaping Matrices 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!

Translated by