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 @@@
- References:
- Sorting Rows of a Matrix
- From: Gregory Lypny <gregory.lypny@videotron.ca>
- Sorting Rows of a Matrix