Take the 2-minute tour ×
Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

I want to sort table including its legend for graph

I have table similar to

M1   M2   M3 
1     5    2
3     1    4 
4     2   -10
5     7    11
6    -2    1

I want the labellings M1, M2 and M3 to move with the first row of numbers while sorting by row basis.

    M1   M3   M2 
    1     2    5
    ...........
     ...........

OK The code is below

(* Initial matrix *)
h = {{M1, M2, M3}, {1, 5, 2}, {3, 1, 4}, {4, 2, -10}, {7, 5, 11}, {6, -2, 1}}

then sorting by basis h1 = Sort /@ h gives

 M1,   M2,  M3
 1,    2,  5
 1,    3,  4
 -10,  2,  4
 5,    7,  11
 -2,   1,  6

I want M1, M2 and M3 to be together with the fist row of numerical values since they are labellings attached to the first numerical values of each column

AS

M1   M3   M2 
1     2    5

..... ....

In that way it will be easy to put the legend in graphs

share|improve this question
1  
Please post a code example for the list definition –  belisarius Dec 23 '13 at 14:01

2 Answers 2

t = {{"M1", "M2", "M3"}, {1, 5, 2}, {3, 1, 4}}
Join[{t[[1, Ordering[t[[2]]]]]}, Sort /@ t[[2 ;;]]] // TableForm
(*
    M1  M3  M2
    1   2   5
    1   3   4
*)
share|improve this answer

There are several ways to do this. belisarius already showed what is perhaps the best, using Ordering. Another is a decorate-and-sort. In steps:

h = {{M1, M2, M3}, {1, 5, 2}, {3, 1, 4}, {4, 2, -10}, {7, 5, 11}, {6, -2, 1}};

{Thread[#2 -> #], ##2} & @@ h

Sort /@ %

{Last /@ #, ##2} & @@ %
{{1 -> M1, 5 -> M2, 2 -> M3}, {1, 5, 2}, {3, 1, 4}, {4, 2, -10}, {7, 5, 11}, {6, -2, 1}}

{{1 -> M1, 2 -> M3, 5 -> M2}, {1, 2, 5}, {1, 3, 4}, {-10, 2, 4}, {5, 7, 11}, {-2, 1, 6}}

{{M1, M3, M2}, {1, 2, 5}, {1, 3, 4}, {-10, 2, 4}, {5, 7, 11}, {-2, 1, 6}}

As one line:

{Last /@ #, ##2} & @@ Sort /@ {Thread[#2 -> #], ##2} & @@ h

In the code above I used Rule (short form ->) arbitrarily; Sort works on other heads as well as List.

Ordering is more concise however, e.g. either of these:

Join[{#[[Ordering@#2]]}, Sort /@ {##2}] & @@ h   (* belisarius's code refactored *)

MapThread[Part, {h, {#2, ##2} & @@ Ordering /@ h}]
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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