How is the sort() working in matlab?
Code in pure matlab:
q is an array:
q = -0.2461 2.9531 -15.8867 49.8750 -99.1172 125.8438 -99.1172
49.8750 -15.8867 2.9531 -0.2461
After q = sort(roots(q)), I got:
q = 0.3525
0.3371 - 0.1564i
0.3371 + 0.1564i
0.2694 - 0.3547i
0.2694 + 0.3547i
1.3579 - 1.7880i
1.3579 + 1.7880i
2.4410 - 1.1324i
2.4410 + 1.1324i
2.8365
Well, seems to work fine! Then in python, I use (q is the same as above, it is an np.array):
import numpy as np
q = np.sort(np.roots(q))
And I got:
[ 0.26937874-0.35469815j 0.26937874+0.35469815j 0.33711562-0.15638427j
0.33711562+0.15638427j 0.35254298+0.j 1.35792218-1.78801226j
1.35792218+1.78801226j 2.44104520-1.13237431j 2.44104520+1.13237431j
2.83653354+0.j ]
Well… These two results seem different in that they sort differently, so what are the reasons? did I make something wrong? thank you in advance!
My answer:
def sortComplex(complexList):
complexList.sort(key=abs)
# then sort by the angles, swap those in descending orders
return complexList
Then call it in the python code, works fine :p
From the MATLAB documentation for SORT:
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:
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: