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

  • 5
    $\begingroup$ Try Matrix[[All, Ordering[First[Matrix]]]]. $\endgroup$ – J. M. is in limbo Oct 17 '18 at 23:43
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):

 SortBy[Table[{myMatrix[[1, i]], myMatrix[[2, i]]}, 
   {i, 4}], #[[1]] &]]
  • $\begingroup$ Perhaps, you meant Matrix instead of myMatrix. $\endgroup$ – bbgodfrey Oct 18 '18 at 0:12
  • 1
    $\begingroup$ 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. $\endgroup$ – David G. Stork Oct 18 '18 at 0:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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