# Double Sorting a Matrix

Say I have two matrices

{{0, 1, 2, 2},
{2, 1, 0, 2}}


and

{{2, 1, 0, 2},
{2, 1, 2, 0}}


I then sort by the first row to get {{0, 1, 2, 2}, {2, 1, 0, 2}} and {{0, 1, 2, 2}, {2, 1, 2, 0}}.

Now I would like to further sort the elements of the lower row which correspond to the same value in the upper row. In this particular case, the last two columns of the upper row have the same value, 2, thus I want to sort those last two columns in the lower row.

If done correctly, we would expect both of the matrices above to reduce to

{{0, 1, 2, 2},
{2, 1, 0, 2}}


Thanks for your help!

## 1 Answer

What I think you are asking for can be achieved by 1) pairing up the values in the two rows (using Transpose) 2) Sorting by the First value in each pair using SortBy 3) Unpairing, again using Transpose. Specifically

lists = {{2, 1, 0, 2}, {2, 1, 2, 0}}
SortBy[Transpose[lists], First] // Transpose

• Great, it works exactly as desired! And so simple I really should've thought of it myself. Thanks! – physicist-trying-to-program Jun 24 '16 at 21:15