Python matlab是如何进行排序的?
sort()在matlab中的工作情况如何?Python matlab是如何进行排序的?,python,matlab,numpy,Python,Matlab,Numpy,sort()在matlab中的工作情况如何? 纯matlab中的代码: q是一个数组: 在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.ar
纯matlab中的代码:
q是一个数组:
在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
):
我得到:
嗯。。。这两个结果似乎不同,因为它们排序不同,那么原因是什么呢?我做错什么了吗?提前谢谢你
我的答覆是:
def sortComplex(complexList):
complexList.sort(key=abs)
# then sort by the angles, swap those in descending orders
return complexList
然后在python代码中调用它,工作正常:p来自以下MATLAB文档: 如果
A
具有复杂条目r
和s
,
排序
根据
以下规则:r
出现在中的s
之前
排序(A)
如果出现以下任一情况
持有:
abs(右)
和abs(r)=abs(s)
angle(r)
复数的排序顺序为 词典学。如果真的和 虚部是非nan的,那么 顺序是由真实的部分决定的 除非它们相等,其中 如果订单由 虚部 换句话说,具有复杂项的数组首先基于项的实部进行排序,并且具有相等实部的任何项都基于其虚部进行排序 编辑: 如果要在MATLAB中重现numpy行为,可以使用函数根据数组项的和组件创建排序索引,然后将该排序索引应用于复杂值数组:
>> 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:啊哈,我知道了,但是np.sort()和matlab中的sort()不一样吗?你的答案是matlab sort的文档,我不确定np.sort()的工作原理是什么?“复数的排序顺序是字典式的。[…]”:@gnoivce:好的,我明白了,谢谢,这是否意味着我必须为matlab中的相同目的编写一个新的sort()??或者我可以用numpy直接调用另一个函数吗???@serina:我更新了答案,向您展示了在MATLAB中重现numpy行为的一种方法。试试
roots(q)[abs(roots(q)).argsort()]
我刚刚试过。。(当然,您需要导入适当的模块)
[ 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)
# then sort by the angles, swap those in descending orders
return complexList
>> 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