MathGroup Archive 2006

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

Search the Archive

Re: Sorting Rows of a Matrix


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 an example using the *Ordering* built-in function:

In[1]:=
m={{1,a},{2,d},{3,c},{4,e},{5,b},{6,f}};

In[2]:=
m//MatrixForm//OutputForm

Out[2]//OutputForm=
1   a

2   d

3   c

4   e

5   b

6   f

In[3]:=
m=m[[Ordering[m[[All,2]]]]]

Out[3]=
{{1,a},{5,b},{3,c},{2,d},{4,e},{6,f}}

In[4]:=
m//MatrixForm//OutputForm

Out[4]//OutputForm=
1   a

5   b

3   c

2   d

4   e

6   f

Best regards,
/J.M.


  • Prev by Date: Re: Sorting Rows of a Matrix
  • Next by Date: Re: laplace transform
  • Previous by thread: Re: Sorting Rows of a Matrix
  • Next by thread: Mathlink with VC++ 8