Mathematica 9 is now available
Services & Resources / Wolfram Forums
-----
 /
MathGroup Archive
2006
*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 2006

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

Search the Archive

Re: Sorting Rows of a Matrix

  • To: mathgroup at smc.vnet.net
  • Subject: [mg65125] Re: [mg65089] Sorting Rows of a Matrix
  • From: János <janos.lobb at yale.edu>
  • Date: Wed, 15 Mar 2006 06:28:48 -0500 (EST)
  • References: <200603141100.GAA24159@smc.vnet.net>
  • Sender: owner-wri-mathgroup at wolfram.com

On Mar 14, 2006, at 6:00 AM, Gregory Lypny wrote:

> Hello everyone,
>
> How can I sort the rows of a matrix by using one or more of the
> columns as sort keys just like in a spreadsheet?  For example, if
> matrix M is 12 x 2 with numbers in the first column and unordered
> month numbers in the second, how would I order the rows by month?
>
> 	Regards,
>
> 		Greg

Hi Gregory,

Here is a newbie approach, by looking the Help of Sort

In[1]:=
m = Table[{Random[Real,
      {-1., 1.}], Random[
      Integer, {1, 12}]},
    {i, 12}]
Out[1]=
{{-0.7676476847185822, 6},
   {0.5369750141346028, 11},
   {-0.9853782613920345, 9},
   {-0.7646868497914143, 5},
   {-0.7626707476232835, 9},
   {-0.844998188870618, 3},
   {-0.02835599687162005, 7},
   {0.3449960852431453, 1},
   {-0.22618623898101198, 10},
   {-0.5062972714869366, 2},
   {0.5275544688424565, 10},
   {0.3876388931584758, 3}}

Just sorting them on the second column:

In[3]:=
m[[Ordering[m[[All,{2}]]]]]
Out[3]=
{{0.3449960852431453, 1},
   {-0.5062972714869366, 2},
   {-0.844998188870618, 3},
   {0.3876388931584758, 3},
   {-0.7646868497914143, 5},
   {-0.7676476847185822, 6},
   {-0.02835599687162005, 7},
   {-0.9853782613920345, 9},
   {-0.7626707476232835, 9},
   {-0.22618623898101198, 10},
   {0.5275544688424565, 10},
   {0.5369750141346028, 11}}

If you want the first column also sorted after the sort on the second  
column is done, you can do:

In[5]:=
m[[Ordering[m[[All,{2, 1}]]]]]
Out[5]=
{{0.3449960852431453, 1},
   {-0.5062972714869366, 2},
   {-0.844998188870618, 3},
   {0.3876388931584758, 3},
   {-0.7646868497914143, 5},
   {-0.7676476847185822, 6},
   {-0.02835599687162005, 7},
   {-0.9853782613920345, 9},
   {-0.7626707476232835, 9},
   {-0.22618623898101198, 10},
   {0.5275544688424565, 10},
   {0.5369750141346028, 11}}

János


--------------------------------------------
f @@ # & /@ ===  f @@@


  • Prev by Date: Re: Factoring
  • Next by Date: Re: Factoring
  • Previous by thread: Re: Sorting Rows of a Matrix
  • Next by thread: Re: Sorting Rows of a Matrix