如何对包含向量的列表进行排序?

时间:2018-12-01 09:13:10

标签: julia

我有一个清单,其中包括二维的一些要点。 例如

List=[270 180 -180;-570 -510 -67.5]

我要按元素1排序

List=[-180 180 270;-67.5 -510 -570]

当我使用排序功能时,代码会给我这个列表

-180.0   180.0  270.0
-570.0  -510.0  -67.5

如何获取该列表。

请帮助我。感谢您的帮助。

2 个答案:

答案 0 :(得分:2)

Instead of using indexin to "reverse search" each sorted element, as user172056 proposes, I would recommend building a sorting permutation for the first row and indexing with that:

julia> l[:, sortperm(view(l, 1, :))]
2×3 Array{Float64,2}:
 -180.0   180.0   270.0
  -67.5  -510.0  -570.0

If you also plan to sort by the second row later, it might also be necessary to specify a stable sorting algorithm (sortperm by default seems to use an unstable one):

julia> l[:, sortperm(view(l, 1, :), alg = Base.Sort.DEFAULT_STABLE)]
2×3 Array{Float64,2}:
 -180.0   180.0   270.0
  -67.5  -510.0  -570.0

答案 1 :(得分:0)

因此,您有一个对象List,它实际上是我假定的具有2行多列的2D数组。每列代表一对坐标,并且您希望基于例如已排序的第一行坐标来排序List。我会这样:

SortRow=List[1,:]
3-element Array{Float64,1}:
270.0
180.0
-180.0

排序此元素,使用indexin内置函数获取索引:

IndexRow=indexin(sort(SortRow),SortRow)
3-element Array{Union{Nothing, Int64},1}:
3
2
1

现在重建List对象:

SortedPoints = List[:,IndexRow]
2×3 Array{Float64,2}:
-180.0   180.0   270.0
-67.5  -510.0  -570.0
相关问题