MathGroup Archive 2002

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

Search the Archive

RE: Friendly Challenge 2: sort by column

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

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).

Notes:
- 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]]:=
    RotateRight[#,n-1]&/@Sort[RotateLeft[#,n-1]&/@m]

ColumnSort[m_?MatrixQ,n_Integer,p_]/;1<=n<=Last[Dimensions[m]]:=
    Sort[m,p[Part[#1,n],Part[#2,n]]&]
    
-------

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.

  m={{65,-5,6},{34,Pi,7},{8,Sqrt[70],8},{12,Sin[2],7}};
  ColumnSort[m, 2, Less]

------
Regards,
  Ted Ersek
  Get Mathematica tips, tricks from
  http://www.verbeia.com/mathematica/tips/Tricks.html





  • 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