From the MATLAB documentation for SORT:
If
A
has complex entriesr
ands
,sort
orders them according to the following rule:r
appears befores
insort(A)
if either of the following hold:
abs(r) < abs(s)
abs(r) = abs(s)
andangle(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