加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

python – matlab如何进行排序?

发布时间:2020-12-17 00:50:39 所属栏目:Python 来源:网络整理
导读: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.33

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):

import numpy as 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)
    # then sort by the angles,swap those in descending orders
    return complexList   

然后在python代码中调用它,工作正常:p

最佳答案
从SORT的MATLAB文档:

If A has complex entries r and s,
sort orders them according to the
following rule: r appears before s in
sort(A) if either of the following
hold:

  • abs(r) < abs(s)
  • abs(r) = abs(s) and angle(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          

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读