3
$\begingroup$

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!

$\endgroup$
0

1 Answer 1

8
$\begingroup$

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
$\endgroup$
1
  • $\begingroup$ Great, it works exactly as desired! And so simple I really should've thought of it myself. Thanks! $\endgroup$ Jun 24, 2016 at 21:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.