4
votes

I am trying to figure out how MATLAB compares complex numbers using the following code. I am not sure if this is expected behavior or if I have uncovered a bug.

The documentation for max says the following:

When X is complex, the maximum is computed using the magnitude MAX(ABS(X)). In the case of equal magnitude elements, then the phase angle MAX(ANGLE(X)) is used.

The behavior of max matches 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 greater than operator, ">", matlab seems to use just 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 any particular reason the behavior changes in this manner from max to > ?

1
"Greater than" and "less than" are not well defined for complex numbers, so you could expect any result.Joni
@Joni I understand that they are not well defined. I was asking this within the scope of MATLAB which chose to have different interpretations for different functions.Pavan Yalamanchili
13 years ago, there was a long discussion about this on MATLAB Central. It seems that not much has changed since then. The answer then as now is that if you want to compare complex numbers, you have to be explicit as to exactly what metric you want to use for greater or less than.craigim
@craigim Thanks for the link. It's a bit discouraging that this is a long known problem and we don't know why this was done.Pavan Yalamanchili
The behavior of > (a.k.a. gt), and the other five relop relationship operators, is detailed in their own documentation.horchler

1 Answers

3
votes

This is from

doc >

The test compares only the real part of numeric arrays

It so happens that the implementations of > looks only at the real part. The design decision from the Matlab team seems legit.

The overwhelming majority of operations that involve the comparison operator are intended to work with real numbers. Adding a special behavior for a basic operation like > to handle complex numbers will cause a big on hit for the 90% of code that does not require it. Especially, that there is not standard way to compare complex numbers. It depends on your application.