Julia: Sort Matrix by column 2 then 3

僤鯓⒐⒋嵵緔 提交于 2021-02-17 14:47:04

问题


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

回答1:


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.



来源:https://stackoverflow.com/questions/23187752/julia-sort-matrix-by-column-2-then-3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!