简体   繁体   中英

Sorting a matrix by the first column Julia

I have a matrix like this in Julia:

5×2 Array{Float64,2}:
5.52777     7.51186e15
0.00444418  0.0311171 
3.26441     9.72657   
3.38447     1.7144e16 
0.459852    6.90901   

I would like to order it by the first column and obtain something like this:

0.00444418  0.0311171 
0.459852    6.90901   
3.26441     9.72657   
3.38447     1.7144e16 
5.52777     7.51186e15

How can I do this?

The expected result you posted doesn't show that you want to order it by the first column, so it's not clear what you want.

If you want to sort the matrix by its first column you can use sortperm and indexing:

julia> m[sortperm(m[:,1]),:]
5×2 Array{Float64,2}:
 0.00444418  0.0311171 
 0.459852    6.90901   
 3.26441     9.72657   
 3.38447     1.7144e16 
 5.52777     7.51186e15

sortperm(m[:,1]) returns the sorted indices of the first column which you then use to index the matrix.

A probably faster alternative would be to use sortslices(m,dims=1) , but this gets a little bit more difficult to call if eg you want to sort by the second column...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM