matlab怎么做呢?

ser*_*ina 5 python matlab numpy

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
Run Code Online (Sandbox Code Playgroud)

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

np.array

import numpy as np
q = np.sort(np.roots(q))
Run Code Online (Sandbox Code Playgroud)

):

[ 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        ]
Run Code Online (Sandbox Code Playgroud)

def sortComplex(complexList):
    complexList.sort(key=abs)
    # then sort by the angles, swap those in descending orders
    return complexList   
Run Code Online (Sandbox Code Playgroud)

q = -0.2461    2.9531  -15.8867   49.8750  -99.1172  125.8438  -99.1172   
49.8750  -15.8867    2.9531   -0.2461
Run Code Online (Sandbox Code Playgroud)

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代码中调用它,工作正常:p

gno*_*ice 4

来自SORT的 MATLAB 文档:

如果A有复杂的条目rssort则根据以下规则对它们进行排序:如果满足以下任一条件,r则出现在sin 之前:sort(A)

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

换句话说,具有复数条目的数组首先根据这些条目的绝对值(即复数大小)进行排序,并且具有相同绝对值的任何条目根据它们的相位角进行排序。

Python(即 numpy)对事物的排序不同。从Amro 在他的评论中链接到的文档

复数的排序顺序是字典顺序。如果实部和虚部均非 nan,则阶数由实部确定,除非它们相等,在这种情况下,阶数由虚部确定。

换句话说,具有复杂条目的数组首先根据条目的实部进行排序,并且具有相同实部的任何条目都根据其虚部进行排序。

编辑:

如果您想在 MATLAB 中重现 numpy 行为,一种方法是使用函数SORTROWS根据数组条目的实部虚部创建排序索引,然后将该排序索引应用于复数数组价值观:

>> 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          
Run Code Online (Sandbox Code Playgroud)

  • “复数的排序顺序是字典顺序。[...]”:http://docs.scipy.org/doc/numpy/reference/ generated/numpy.sort.html (2认同)