This is my list

Matrix = {{1, -2, 3, -4}, {{a, b}, {f, e}, {a, b}, {f, e}}}

I want to order the columns in ascending order depending on the values on the first row. I Expect something like

{{-4, -2, 1, 3}, {{f, e}, {f, e}, {a, b}, {a, b}}}

I've tried the Sort function, but it just returns the initial value

up vote 6 down vote accepted
Transpose[SortBy[Transpose[Matrix], First]]

{{-4, -2, 1, 3}, {{f, e}, {f, e}, {a, b}, {a, b}}}

Transpose[Transpose[#][[Ordering @ First @ #]]] &@ Matrix

{{-4, -2, 1, 3}, {{f, e}, {f, e}, {a, b}, {a, b}}}

Renaming Matrix to myMatrix (so as to avoid starting a variable name with an upper-case letter):

Transpose[
 SortBy[Table[{myMatrix[[1, i]], myMatrix[[2, i]]}, 
   {i, 4}], #[[1]] &]]
  • Perhaps, you meant Matrix instead of myMatrix. – bbgodfrey Oct 18 at 0:12
  • 1
    Yes... in my personal code I changed the name because we must never use an upper-case letter to start the name of a variable, lest it conflict with internal definitions. Thanks. Solution amended. – David G. Stork Oct 18 at 0:15

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

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