Question

I would like to sort my matrix A by column 2 then 3.

A = round.(randn(100,4))

Maybe something like:

sort(A,(0,2:3))
100x4 Array{Float64,2}:
  0.0  -2.0  -2.0  -1.0
 -1.0  -2.0  -1.0   1.0
  1.0  -2.0  -1.0   2.0
 -1.0  -2.0   0.0   0.0
 -1.0  -2.0   0.0  -1.0
 -0.0  -2.0   0.0  -1.0
  1.0  -2.0   0.0   0.0
  1.0  -2.0   1.0  -1.0
 -0.0  -2.0   2.0  -1.0
 -0.0  -1.0  -2.0   1.0
  ⋮                    
 -0.0   1.0   0.0   1.0
  1.0   1.0   1.0   1.0
  0.0   1.0   1.0  -1.0
 -0.0   1.0   2.0   0.0
 -0.0   2.0  -1.0   0.0
 -2.0   2.0  -1.0   1.0
  2.0   2.0  -0.0  -1.0
 -1.0   2.0  -0.0  -1.0
  1.0   2.0   0.0   2.0
 -1.0   2.0   2.0   0.0
Was it helpful?

Solution

There is a sortrows function that takes a by keyword that lets you do this:

julia> sortrows(A, by=x->(x[2],x[3]))
100x4 Array{Float64,2}:
  2.0  -3.0  -0.0   0.0
 -1.0  -2.0  -1.0  -1.0
 -0.0  -2.0  -0.0   0.0
  0.0  -2.0   0.0  -1.0
  1.0  -2.0   1.0   2.0
 -0.0  -2.0   1.0  -1.0
 -1.0  -1.0  -2.0   1.0
 -1.0  -1.0  -2.0  -0.0
 -1.0  -1.0  -1.0   1.0
 -0.0  -1.0  -1.0   0.0
  ⋮
 -0.0   1.0   1.0  -1.0
 -0.0   1.0   2.0   1.0
  0.0   1.0   2.0   0.0
 -1.0   2.0  -2.0   1.0
  0.0   2.0  -2.0  -2.0
  1.0   2.0  -1.0   0.0
  0.0   2.0  -1.0  -0.0
 -1.0   2.0   0.0  -1.0
 -0.0   2.0   2.0   0.0
  1.0   3.0   2.0   1.0

The sorting API is pretty flexible – you can find documentation here.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top