views:

120

answers:

1
+3  A: 

From the MATLAB documentation for SORT:

If A has complex entries r and s, sort orders them according to the following rule: r appears before s in sort(A) if either of the following hold:

  • abs(r) < abs(s)
  • abs(r) = abs(s) and angle(r) < angle(s)

In other words, an array that has complex entries is first sorted based on the absolute value (i.e. complex magnitude) of those entries, and any entries that have the same absolute value are sorted based on their phase angles.

Python (i.e. numpy) orders things differently. From the documentation Amro linked to in his comment:

The sort order for complex numbers is lexicographic. If both the real and imaginary parts are non-nan then the order is determined by the real parts except when they are equal, in which case the order is determined by the imaginary parts.

In other words, an array that has complex entries is first sorted based on the real component of the entries, and any entries that have equal real components are sorted based on their imaginary components.

EDIT:

If you want to reproduce the numpy behavior in MATLAB, one way you can do it is to use the function SORTROWS to create a sort index based on the real and imaginary components of the array entries, then apply that sort index to your array of complex values:

>> r = roots(q);  %# Compute your roots
>> [junk,index] = sortrows([real(r) imag(r)],[1 2]);  %# Sort based on real,
                                                      %#   then imaginary parts
>> r = r(index)  %# Apply the sort index to r

r =

   0.2694 - 0.3547i
   0.2694 + 0.3547i
   0.3369 - 0.1564i
   0.3369 + 0.1564i
   0.3528          
   1.3579 - 1.7879i
   1.3579 + 1.7879i
   2.4419 - 1.1332i
   2.4419 + 1.1332i
   2.8344          
gnovice
@gnovice: aha, I got it, but np.sort(), wasn't it the same as the sort() in matlab? your answer is the doc for matlab sort, I am not sure what the np.sort() works?
serina
"The sort order for complex numbers is lexicographic. [...]": http://docs.scipy.org/doc/numpy/reference/generated/numpy.sort.html
Amro
@Amro: I got it, thanks
serina
@gnovice: obviously...
serina
@gnoivce: Okay, I see, thanks, so does that mean I have to write a new sort() for the same purpose as that in matlab?? or is there another function I could call directly with numpy??
serina
@serina: I updated my answer to show you one way to reproduce the numpy behavior in MATLAB.
gnovice
@gnovice: omg...thank you!
serina