필터 지우기
필터 지우기

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

조회 수: 43 (최근 30일)
lil brain
lil brain 2022년 3월 1일
편집: Stephen23 2022년 3월 2일
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
lil brain
lil brain 2022년 3월 2일
Does throwing away the imaginary part change its value? I essentially want to keep them as comparable to non.imaginary numbers as possible. Thanks!
Stephen23
Stephen23 2022년 3월 2일
편집: Stephen23 2022년 3월 2일
"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.

댓글을 달려면 로그인하십시오.

답변 (3개)

John D'Errico
John D'Errico 2022년 3월 1일
편집: John D'Errico 2022년 3월 1일
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 2022년 3월 2일
편집: David Goodmanson 2022년 3월 2일
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 2022년 3월 1일
How about using isreal function?

카테고리

Help CenterFile Exchange에서 Performance and Memory에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by