Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Julia: Sort Matrix by column 2 then 3

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
like image 719
Francis Smart Avatar asked Apr 20 '14 21:04

Francis Smart


People also ask

How do you arrange a matrix in ascending order?

B = sort( A ) sorts the elements of A in ascending order. If A is a vector, then sort(A) sorts the vector elements. If A is a matrix, then sort(A) treats the columns of A as vectors and sorts each column.


1 Answers

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.

like image 134
StefanKarpinski Avatar answered Sep 21 '22 10:09

StefanKarpinski