# 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:** 1\
**Showing post:** 5

<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

```

---

_[View the full topic](https://discourse.julialang.org/t/sort-matrix-based-on-the-elements-of-a-specific-column/23475)._
