MathGroup Archive 2004

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

Search the Archive

Re: Sorting (again!), but with multiple columns

  • To: mathgroup at smc.vnet.net
  • Subject: [mg50421] Re: [mg50417] Sorting (again!), but with multiple columns
  • From: Sseziwa Mukasa <mukasa at jeol.com>
  • Date: Fri, 3 Sep 2004 03:35:04 -0400 (EDT)
  • References: <200409020835.EAA02137@smc.vnet.net>
  • Sender: owner-wri-mathgroup at wolfram.com

On Sep 2, 2004, at 4:35 AM, DIAMOND Mark R. wrote:

> First, I want to sort a (100000 x 3) matrix so that it is sorted
> firstly on
> column 2 (ascending order) and then subsorted on column 3 (decending
> order).
> I had thought incorrectly, that the evaluation order of And[] would
> lead the
> following to work ... I've written the predicate out separately just
> to make
> it clearer.
>
> tQ23[t1_, t2_] :=
>   OrderedQ[{t1[[2]], t2[[2]]}] \[And] OrderedQ[{t2[[3]], t1[[3]]}]
>
> t = Table[{i, j, k}, {i, 2}, {j, 2}, {k, 2}];
> Sort[t, tQ23]
>
> {{1, 1, 2}, {2, 1, 2}, {1, 2, 2}, {2, 2, 2}, {1, 1, 1}, {2, 1, 1}, {1,
> 2,
>     1}, {2, 2, 1}}
>

Your table expression does not result in a matrix, it results in a list
4 levels deep, but the following expression does what you want

Sort[Flatten[Table[{i, j,
     k}, {i, 2}, {j, 2}, {k, 2}], 2], #[[2]] == #2[[2]] == 
#[[3]] <=
#2[[3]] &]

> Second, I want to sort a (100000 x 3) matrix so that it is soted first
> on
> column 2 (ascending order), then *conditionally* subsorted on column
> 3, with
> ascending order if column 2 is Even, and decending if column 2 is Odd.
> I
> have no idea how to approach this, except by sorting on column 2,
> stripping
> out blocks of rows, and resorting them before appending them to a new
> list.
> This is horribly slow. Any suggestions? Any speed-up, or flash of
> insight
> would be most appreciated.

You could split the list on the second element after sorting, then use
Map to do the sorts on the third element, then flatten to restore the
structure

Flatten[If[EvenQ[#[[1, 2]]], Sort[#, #[[3]] == #2[[3]] &],
         Sort[#, #[[3]] == #2[[3]] &]] & /@ Split[Sort[Flatten[
         Table[{i, j, k}, {
           i, 2}, {j, 2}, {k, 2}], 2], #[[2]] == #2[[2]] &], #[[2]] 
==
#2[[2]] &], 1]

I haven't optimized for speed, the second expression take 287 seconds
on a 1 million row array of integers on my machine a 1GHz G4 PowerMac.

Regards,

Ssezi


  • Prev by Date: Re: Use of large memory
  • Next by Date: Re: newbie is looking for a customDistribution function
  • Previous by thread: Sorting (again!), but with multiple columns
  • Next by thread: Re: Sorting (again!), but with multiple columns