Matlab function for calculating phase of complex number
Show older comments
Hello and good day to all,
Matlab has a built in function to calculate amplitude and phase of a complex number using abs(number) and angle(number) funstions. I have a question regarding phase part. Lets suppose we have a complex number in the form z=x+jy (x being your real and y your imaginary part). When you want to calculate the phase of this number the formula is phase=arctan(y/x). In addition to this formula we have to take care of sign's of real and imaginary part (especially real part)and correspondingly we add (+/-) pi to the calculated value. Does matlab "angle function" consider this thing because all examples I saw have only positive real parts. Thank you
Answers (1)
John D'Errico
on 9 Aug 2016
Edited: John D'Errico
on 9 Aug 2016
Actually, the formula is
atan2(y,x)
atan2 handles the problem properly, working in all 4 quadrants. If you don't believe me, just look in the angle function itself. There you will find only one line of code:
p = atan2(imag(h), real(h));
Yep.
angle(-1-0.5i)
ans =
-2.67794504458899
4 Comments
ehtisham asghar
on 9 Aug 2016
John D'Errico
on 9 Aug 2016
A virtue of atan2 is it also always works even when x==0. atan works there too, at least it does in MATLAB.
I think just about every computer language seems to have an atan2 function, that takes the two arguments, instead of the ratio. That ratio screws things up, because it yields only a two quadrant solution. It can be repaired without TOO much effort. We have a simple identity:
atan2(y,x) == atan(y./x) + (x<0)*pi - (x<0 & y<0)*2*pi
That seems to work for all quadrants. I can probably write it more simply.
Walter Roberson
on 10 Aug 2016
That would not work correctly for (0,0) because the 0/0 would give rise to NaN and atan(NaN) is NaN which would pollute the rest of the calculation.
John D'Errico
on 10 Aug 2016
True. 0/0 will be a problem.
Categories
Find more on Switches and Breakers 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!