Mathematica 9 is now available
Services & Resources / Wolfram Forums
-----
 /
MathGroup Archive
2005
*January
*February
*March
*April
*May
*June
*July
*August
*September
*October
*November
*December
*Archive Index
*Ask about this page
*Print this page
*Give us feedback
*Sign up for the Wolfram Insider

MathGroup Archive 2005

[Date Index] [Thread Index] [Author Index]

Search the Archive

Re: Sorting on multiple columns within a matrix

  • To: mathgroup at smc.vnet.net
  • Subject: [mg57856] Re: Sorting on multiple columns within a matrix
  • From: János <janos.lobb at yale.edu>
  • Date: Fri, 10 Jun 2005 02:29:19 -0400 (EDT)
  • References: <200506090918.FAA28665@smc.vnet.net>
  • Sender: owner-wri-mathgroup at wolfram.com

On Jun 9, 2005, at 5:18 AM, Lee Newman wrote:

> Hello,
>
> I can't come up with a solution to the following simple task:
>
> -  I have a matrix, let's M={ {"Z",2,"a"},{"A",2,"k"}, {"Z",1,"z"},
> {"A",1,"a"},{"Z",3,"k"}, {"A",3,"z"} }
> -  I want to be able to sort the matrix row-wise, based on multiple
> columns, for example sort first on column 2 (ascending) and then
> secondly on column1 (ascending)
>
> desired result:
> A 1 a
> Z 1 z
> A 2 k
> Z 2 a
> A 3 z
> Z 3 k
>
> I suspect the solution involves using a pure function of some form as
> the second argument in the Sort function, but I can't figure out what
> this function should be.
>
> Thanks,
> Lee
>

The solution to it is in the Help under the Sort examples.  Here it  
is for this case:

In[1]:=
mm = {{"Z", 2, "a"},
     {"A", 2, "k"}, {"Z", 1,
      "z"}, {"A", 1, "a"},
     {"Z", 3, "k"}, {"A", 3,
      "z"}};

In[2]:=
ColumnForm[mm]
Out[2]=
{"Z", 2, "a"}
{"A", 2, "k"}
{"Z", 1, "z"}
{"A", 1, "a"}
{"Z", 3, "k"}
{"A", 3, "z"}

In[15]:=
nn = mm[[Ordering[mm[[All,
       {2, 1}]]]]];

In[16]:=
ColumnForm[nn]
Out[16]=
{"A", 1, "a"}
{"Z", 1, "z"}
{"A", 2, "k"}
{"Z", 2, "a"}
{"A", 3, "z"}
{"Z", 3, "k"}

János


  • Prev by Date: Re: character range on lower case script alphabet
  • Next by Date: Re: Sorting on multiple columns within a matrix
  • Previous by thread: Sorting on multiple columns within a matrix
  • Next by thread: Re: Sorting on multiple columns within a matrix