sort()在matlab中是如何工作的?
纯matlab代码:
q是一个数组:
After 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
):
我得到了:
[ 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
在 然后在python代码中调用它,效果很好:p
来自SORT的MATLAB文档:
换言之,具有复杂项的数组首先基于这些项的absolute value(即复数幅度)排序,并且任何具有相同绝对值的项都基于它们的phase angles排序。在
Python(即numpy)的顺序不同。从the documentation Amro linked to in his comment:
换言之,具有复杂条目的数组首先根据条目的实分量进行排序,而具有相等实分量的任何条目都将基于它们的虚分量进行排序。在
编辑:
如果要在MATLAB中重现numpy行为,一种方法是使用函数SORTROWS根据数组项的real和{a7}组件创建排序索引,然后将该排序索引应用于复杂值数组:
相关问题 更多 >
编程相关推荐