# Sort matrix based on the elements of a specific column

**URL:** <https://discourse.julialang.org/t/sort-matrix-based-on-the-elements-of-a-specific-column/23475>\
**Category:** General Usage\
**Tags:** sort\
**Created:** [April 24, 2019, 2:14pm UTC](https://discourse.julialang.org/t/sort-matrix-based-on-the-elements-of-a-specific-column/23475 "2019-04-24T14:14:22Z")\
**Posts on this page:** 9\
**Page:** 1

<div class="post-metadata">

**Author:** ![eed](https://avatars.discourse-cdn.com/v4/letter/e/b5ac83/32.png) [@eed](https://discourse.julialang.org/u/eed)\
**Post date:** [April 24, 2019, 2:14pm UTC](https://discourse.julialang.org/t/sort-matrix-based-on-the-elements-of-a-specific-column/23475/1 "2019-04-24T14:14:22Z")

</div>

Hi  
I’m new to Julia but I have some exprience with Matlab.  
I have an array A (mix of numbers and text columns) and I want to sort the rows based on the values on a specific column of A.  
In matlab, the code is:  
B = sortrows(A,column)  
This sorts A based on the columns specified in the vector column. For example, sortrows(A,4) sorts the rows of A in ascending order based on the elements in the fourth column. sortrows(A,[4 6]) first sorts the rows of A based on the elements in the fourth column, then based on the elements in the sixth column to break ties.

Is there a similar command in Julia? I’ve been looking but not yet found the answer

Thanks in advance for the help!

---

<div class="post-metadata">

**Author:** ![Tamas\_Papp](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/tamas_papp/32/25949_2.png) [@Tamas\_Papp](https://discourse.julialang.org/u/Tamas_Papp)\
**Post date:** [April 24, 2019, 2:23pm UTC](https://discourse.julialang.org/t/sort-matrix-based-on-the-elements-of-a-specific-column/23475/2 "2019-04-24T14:23:00Z")

</div>

```julia
A = rand(1:100, 3, 4) # a random matrix
A[sortperm(A[:, 4]), :] # sorted by the 4th column

```

Welcome to Julia!

---

<div class="post-metadata">

**Author:** ![mohamed82008](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/mohamed82008/32/18171_2.png) [@mohamed82008](https://discourse.julialang.org/u/mohamed82008)\
**Post date:** [April 24, 2019, 2:37pm UTC](https://discourse.julialang.org/t/sort-matrix-based-on-the-elements-of-a-specific-column/23475/3 "2019-04-24T14:37:45Z")

</div>

Here is another:

```julia
sortrows(A, i, rev=false) = sortslices(A, dims=1, lt=(x,y)->isless(x[i],y[i]), rev=rev)

```

---

<div class="post-metadata">

**Author:** ![ElOceanografo](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/eloceanografo/32/624_2.png) [@ElOceanografo](https://discourse.julialang.org/u/ElOceanografo)\
**Post date:** [April 24, 2019, 4:05pm UTC](https://discourse.julialang.org/t/sort-matrix-based-on-the-elements-of-a-specific-column/23475/4 "2019-04-24T16:05:49Z")

</div>

If your array has a mix of numeric and text columns, you probably want to be using a [DataFrame](https://juliadata.github.io/DataFrames.jl/stable/index.html) instead. The DataFrames package comes with methods for [sorting](https://juliadata.github.io/DataFrames.jl/stable/man/sorting.html#Sorting-1) by column name or index:

```julia
julia> using DataFrames
julia> df = DataFrame(a = ["b", "a", "a"], x = [4.2, 0, -5.1], 
           y = [3//2, -1//2, 15//16]);
julia> sort(df, :a)
3×3 DataFrame
│ Row │ a │ x │ y │
│ │ String │ Float64 │ Rational… │
├─────┼────────┼─────────┼───────────┤
│ 1 │ a │ 0.0 │ -1//2 │
│ 2 │ a │ -5.1 │ 15//16 │
│ 3 │ b │ 4.2 │ 3//2 │

julia> sort(df, 1)
3×3 DataFrame
│ Row │ a │ x │ y │
│ │ String │ Float64 │ Rational… │
├─────┼────────┼─────────┼───────────┤
│ 1 │ a │ 0.0 │ -1//2 │
│ 2 │ a │ -5.1 │ 15//16 │
│ 3 │ b │ 4.2 │ 3//2 │

```

or by multiple columns:

```julia
julia> sort(df, [:a, :x])
3×3 DataFrame
│ Row │ a │ x │ y │
│ │ String │ Float64 │ Rational… │
├─────┼────────┼─────────┼───────────┤
│ 1 │ a │ -5.1 │ 15//16 │
│ 2 │ a │ 0.0 │ -1//2 │
│ 3 │ b │ 4.2 │ 3//2 │

```

---

<div class="post-metadata">

**Author:** ![nicolas](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/nicolas/32/26439_2.png) [@nicolas](https://discourse.julialang.org/u/nicolas)\
**Post date:** [April 3, 2020, 8:20pm UTC](https://discourse.julialang.org/t/sort-matrix-based-on-the-elements-of-a-specific-column/23475/5 "2020-04-03T20:20:54Z")

</div>

I had the same issue, but I needed to break ties and didn’t want to use DataFrames. Here is a suggestion (the default behavior is like Matlab’s, otherwise one can specify a matrix of elements to sort on):

```julia
function sortrows(M, by=zeros(0))
    if by == zeros(0)
        order = copy(M)
    else
        order = copy(by)
    end
    if size(order,2) > 1
        order = Float64.(order.-minimum(order, dims = 1))
        order = (order./maximum(order,dims=1))*(10).^(size(order,2):-1:1)
    end
    order = sortperm(order[:,1])
    return M[order,:], order
end

A = [4 1 1; 3 2 5;2 4 3]'
sorted_A, order = sortrows(A,A[:,[1,3]])

julia> sorted_A
3×3 Array{Int64,2}:
 1 5 3
 1 2 4
 4 3 2

```

---

<div class="post-metadata">

**Author:** ![jovansam](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/jovansam/32/15023_2.png) [@jovansam](https://discourse.julialang.org/u/jovansam)\
**Post date:** [June 7, 2020, 11:18am UTC](https://discourse.julialang.org/t/sort-matrix-based-on-the-elements-of-a-specific-column/23475/6 "2020-06-07T11:18:23Z")

</div>

In Julia 1.4.2:

```nohighlight
 # generate random matrix
A = rand(4,3)

 # sort by row (dim=1) along column 2
sortslices(A,dims=1,by=x->x[2],rev=false)

 # reverse sort by row (dim=1) along column 2
sortslices(A,dims=1,by=x->x[2],rev=true)

```

---

<div class="post-metadata">

**Author:** ![TheCedarPrince](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/thecedarprince/32/17323_2.png) [@TheCedarPrince](https://discourse.julialang.org/u/TheCedarPrince)\
**Post date:** [October 29, 2023, 5:09pm UTC](https://discourse.julialang.org/t/sort-matrix-based-on-the-elements-of-a-specific-column/23475/7 "2023-10-29T17:09:53Z")

</div>

Out of curiosity, it’s been a few years – do you all suppose this is still the most straightforward approach?

---

<div class="post-metadata">

**Author:** ![rafael.guerra](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/rafael.guerra/32/216610_2.png) [@rafael.guerra](https://discourse.julialang.org/u/rafael.guerra)\
**Post date:** [October 29, 2023, 8:35pm UTC](https://discourse.julialang.org/t/sort-matrix-based-on-the-elements-of-a-specific-column/23475/8 "2023-10-29T20:35:51Z")

</div>

> [@Tamas\_Papp](#):
>
> `A[sortperm(A[:, 4]), :] `

Perhaps we should season the solution with views:

```julia
@views A[sortperm(A[:, 4]), :]

```

---

<div class="post-metadata">

**Author:** ![aplavin](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/aplavin/32/222056_2.png) [@aplavin](https://discourse.julialang.org/u/aplavin)\
**Post date:** [October 30, 2023, 2:12am UTC](https://discourse.julialang.org/t/sort-matrix-based-on-the-elements-of-a-specific-column/23475/9 "2023-10-30T02:12:35Z")

</div>

An arguably cleaner version, and easier to generalize:

```julia
B = stack(sort(eachrow(A), by=r -> r[4]); dims=1)

```

Optics are also nice here:

```julia
using AccessorsExtra
B = @modify(eachrow(A)) do rows
   sort(rows, by=r -> r[4])
end

```
