MathGroup Archive 2002

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

Search the Archive

RE: Friendly Challenge 2: sort by column

  • To: mathgroup at
  • Subject: [mg35058] RE: Friendly Challenge 2: sort by column
  • From: "Ersek, Ted R" <ErsekTR at>
  • Date: Thu, 20 Jun 2002 23:55:08 -0400 (EDT)
  • Sender: owner-wri-mathgroup at

My solution is given below which has the following features.

- I do extensive parameter checking.
- I provide for a user specified ordering function.
- My program uses Sort with the default ordering function when possible 
  (Sort is much faster that way).

- It isn't clear what the desired behavior should be when elements in
elements in column (n) are the same, so I didn't worry about that case.

-If you want to allow for things that aren't strictly matrices remove the (
?MatrixQ ).


ColumnSort::usage="ColumnSort[matrix, n] arranges the matrix rows such that
column n is in canonical order. ColumnSort[matrix, n, p] uses ordering
function p to arrange the rows.";

ColumnSort[m_?MatrixQ, 1]:=Sort[m]

ColumnSort[m_?MatrixQ, n_Integer]/; 1<=n<=Last[Dimensions[m]]:=


You should keep in mind that by default Sort arranges things in canonical
order which may not be numerical order.  In the following example ordering
function Less is needed to numerically sort the second column.

  ColumnSort[m, 2, Less]

  Ted Ersek
  Get Mathematica tips, tricks from

  • Prev by Date: Re: Solve weirdness again
  • Next by Date: RE: Re: Friendly Challenge 2: sort by column
  • Previous by thread: RE: Friendly Challenge 2: sort by column
  • Next by thread: RE: Re: Friendly Challenge 2: sort by column