Comparing Complex Numbers in MATLAB

I am trying to understand how MATLAB compares complex numbers using the following code. I'm not sure if this is the expected behavior or if I have encountered the error.

The documentation for max states the following:

When X is complex, the maximum is calculated using the MAX value (ABS (X)). In the case of elements with the same phase value, the angle MAX (ANGLE (X)) is used.

The behavior is max

consistent with the documentation as expected.

>> a = complex(rand(3,1), rand(3,1))

a =

   0.8147 + 0.9134i
   0.9058 + 0.6324i
   0.1270 + 0.0975i

>> b = complex(imag(a), real(a))

b =

   0.9134 + 0.8147i
   0.6324 + 0.9058i
   0.0975 + 0.1270i

>> max(a, b)

ans =

   0.8147 + 0.9134i
   0.6324 + 0.9058i
   0.0975 + 0.1270i

>> a > b

ans =

     0
     1
     1

>> angle(a) > angle(b)

ans =

     1
     0
     0

>> abs(a) == abs(b)

ans =

     1
     1
     1

      

However, when I try to use more than the ">" operator, Matlab seems to only use the real part for comparison.

>> a = complex(rand(5,1), rand(5,1))

a =

   0.1576 + 0.1419i
   0.9706 + 0.4218i
   0.9572 + 0.9157i
   0.4854 + 0.7922i
   0.8003 + 0.9595i

>> b = complex(imag(a), real(a))

b =

   0.1419 + 0.1576i
   0.4218 + 0.9706i
   0.9157 + 0.9572i
   0.7922 + 0.4854i
   0.9595 + 0.8003i

>> max(a, b) == a

ans =

     0
     0
     0
     1
     1

>> a > b

ans =

     1
     1
     1
     0
     0

>> real(a) > real(b)

ans =

     1
     1
     1
     0
     0

      

Is there a particular reason why the behavior changes in this way from max

to >

?

+3


source to share


1 answer


Its from

doc >

      

The test only compares the real part of numeric arrays



It just so happens that implementations> only look at the real part. The design decision of the Matlab team seems to be legitimate.

The vast majority of operations associated with the comparison operator are designed to work with real numbers. Adding special behavior for a basic operation like> to handle complex numbers will do a lot for 90% of the code that doesn't require it. Moreover, there is no standard way to compare complex numbers. It depends on your application.

+2


source







All Articles