2010-09-07 215 views
5

sort()如何在matlab中工作?
典纯MATLAB:
q是一个数组: matlab如何进行排序?

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

+2

尝试'根(q)' – Amro 2010-09-07 21:44:32

+0

@Amro [ABS(根(q))argsort()]:不,不会工作 – serina 2010-09-07 22:35:32

+0

我只是试了一下..(当然你需要导入正确的模块) – Amro 2010-09-07 22:54:46

回答

4

从MATLAB文档SORT

如果A具有复杂项rssort根据以下规则命令它们::如果下列 保持的s之前只出现在 sort(A)

  • abs(r) < abs(s)
  • abs(r) = abs(s)angle(r) < angle(s)

换言之,其具有复杂的条目的阵列第一排序基于在absolute value(即复合量级),并且具有相同绝对值的任何条目基于它们的phase angles进行排序。

Python(即numpy)命令的内容有所不同。 the documentation Amro linked to in his comment

复数的排序顺序是 lexicographic。如果虚实数和虚数部分都不是nan,则 的顺序由实际部分 决定,除非它们相等,其中 的情况下顺序由虚部决定 。

换言之,具有复杂条目的数组首先基于条目的实际分量进行排序,并且具有相同实际分量的任何条目基于它们的虚数分量进行排序。

编辑:

如果要复制在MATLAB中numpy的行为,你可以做一个方式,是使用功能SORTROWS来创建基于阵列的realimaginary组件的排序索引条目,然后应用排序索引你的复数值数组:

>> 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   
+0

@gnovice:aha,我知道了,但np.sort(),是不是与在MATLAB中的排序()相同?你的答案是matlab排序的文档,我不确定np.sort()的工作原理是什么? – serina 2010-09-07 20:05:16

+2

“为复数的排序顺序是字典[...]。”:http://docs.scipy.org/doc/numpy/reference/generated/numpy.sort.html – Amro 2010-09-07 20:08:53

+0

@Amro:我知道了,谢谢 – serina 2010-09-07 20:10:46