Best way to get rid of/ prevent function from creating complex numbers?
57 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
Hi,
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)
Hurst_nonglitch_h_ref(k)=dfaedit(nonglitch_xyz_h_ref{k},0,0,0);
end
Thanks!
3 commentaires
Stephen23
le 2 Mar 2022
Modifié(e) : Stephen23
le 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.
Réponses (3)
John D'Errico
le 1 Mar 2022
Modifié(e) : John D'Errico
le 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.
0 commentaires
David Goodmanson
le 2 Mar 2022
Modifié(e) : David Goodmanson
le 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.
0 commentaires
Voir également
Catégories
En savoir plus sur Performance and Memory dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!