sort() 在 matlab 中如何工作?
纯matlab代码:
q 是一个数组:
q = -0.2461 2.9531 -15.8867 49.8750 -99.1172 125.8438 -99.1172
49.8750 -15.8867 2.9531 -0.2461
在
q = sort(roots(q))
之后,我得到:
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
好吧,似乎工作正常!然后在python中,我使用(q同上,是一个
np.array
):
将 numpy 导入为 np
q = np.sort(np.roots(q))
我得到了:
[ 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]
嗯……这两个结果看起来不一样,排序不一样,那么是什么原因呢?我做错了什么吗?提前谢谢你!
我的回答:
def sortComplex(complexList):
complexList.sort(key=abs)
# 然后按角度排序,按降序交换
返回复杂列表
然后在 python 代码中调用它,工作正常:p
最佳答案
来自 SORT 的 MATLAB 文档:
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)
换句话说,具有复杂条目的数组首先根据 absolute value 排序。这些条目的(即复数值)以及具有相同绝对值的任何条目都根据它们的 phase angles 进行排序。 .
Python(即 numpy)以不同的方式排序。来自 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.
换句话说,具有复数项的数组首先根据项的实部排序,任何具有相同实部的项根据其虚部排序。
编辑:
如果您想在 MATLAB 中重现 numpy 行为,一种方法是使用函数 SORTROWS基于 real 创建排序索引和 imaginary数组条目的组成部分,然后将该排序索引应用于您的复数值数组:
>> 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
关于python - matlab 是怎么排序的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3662203/