![]() |
Matlab如何进行排序?
在Matlab中sort()如何工作?
纯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 [B]回答:[/B] 从[URL="http://www.mathworks.com/help/techdoc/ref/sort.html"]SORT[/URL]的MATLAB文档中: [INDENT]如果A具有复杂的条目r和s ,则按以下规则sort它们进行sort(A)如果满足以下任一条件,则r在sort(A) s之前出现: [LIST][*] abs(r) < abs(s) [*] abs(r) = abs(s)和angle(r) < angle(s)[/LIST][/INDENT]换句话说,具有复杂条目的阵列首先基于那些条目的[URL="http://www.mathworks.com/help/techdoc/ref/abs.html"]绝对值[/URL] (即,复数幅值)进行排序,并且具有相同绝对值的任何条目都基于其[URL="http://www.mathworks.com/help/techdoc/ref/angle.html"]相角[/URL]进行排序。 Python(即numpy)对事物的排序不同。 [URL="http://docs.scipy.org/doc/numpy/reference/generated/numpy.sort.html"]在他的评论中链接到的Amro文档[/URL] : [INDENT]复数的排序顺序为字典顺序。如果实部和虚部都不都是南,则顺序由实部确定,除非它们相等,在这种情况下,顺序由虚部确定。 [/INDENT]换句话说,首先根据条目的实分量对具有复杂条目的数组进行排序,然后根据虚分量对具有相等实数的任何条目进行排序。 [B]编辑:[/B] 如果要在MATLAB中重现numpy行为,一种方法是使用函数[URL="http://www.mathworks.com/help/techdoc/ref/sortrows.html"]SORTROWS[/URL]根据数组条目的[URL="http://www.mathworks.com/help/techdoc/ref/real.html"]实部[/URL]和[URL="http://www.mathworks.com/help/techdoc/ref/imag.html"]虚部[/URL]创建排序索引,然后将该排序索引应用于复杂数组值: >> 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 [url=https://stackoverflow.com/questions/3662203]更多&回答...[/url] |
所有时间均为北京时间。现在的时间是 23:22。 |
Powered by vBulletin
版权所有 ©2000 - 2025,Jelsoft Enterprises Ltd.