Soma
Soma

Reputation: 743

how can I sort a list including vectors?

I have list including some points in two dimensions. for example

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

I want sort it by element one

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

when I use sort function the code gives me this list

-180.0   180.0  270.0
-570.0  -510.0  -67.5

How can I achieve that list.

Please help me. Thanks for your kindly helps.

Upvotes: 1

Views: 116

Answers (2)

phipsgabler
phipsgabler

Reputation: 20960

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

Upvotes: 2

user172056
user172056

Reputation: 184

So you have an object Listwhich is in fact an 2D array with 2 rows and multiple columns I presume. Each column represents a pair of coordinates and you want a sorted List based on for example the sorted first row of coordinates. I would do it like this:

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

Sort this element, obtain the indices with indexin built-in function:

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

Now reconstruct the List object:

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

Upvotes: 0

Related Questions