Re: how to pick out alternating columns and rows in a matrix?

• To: mathgroup at christensen.cybernetics.net
• Subject: [mg597] Re: [mg551] how to pick out alternating columns and rows in a matrix?
• From: Count Dracula <lk3a at kelvin.seas.virginia.edu>
• Date: Thu, 23 Mar 1995 08:41:37 -0500

Here's a definition for a function to select odd(default) or even (with
sel = EvenQ) rows and columns of a matrix:

altrowcol[(m_)?MatrixQ, sel_:OddQ] :=
m[[Apply[Sequence, (Select[Range[#1], sel] & ) /@ Dimensions[m]]]]

In [mg580] Tyler Perkins perkins at colorado.edu wrote:
> Always remember -- the heart of Mathematica is pattern matching.
> How 'bout this:

> In[1]:=
>  OddOnly[{odd_, even_, rest___}] := Join[{odd}, OddOnly[{rest}]];
>  OddOnly[singleton_] := singleton;

> OddOnly //@ {{11,12,13,14,15},
>              {21,22,23,24,25},
>             {31,32,33,34,35},
>             {41,42,43,44,45},
>             {51,52,53,54,55}}
> Out[3]=
> {{11, 13, 15}, {31, 33, 35}, {51, 53, 55}}

This recursive function works correctly, but is unduly complicated for
the task at hand and will be much slower than the direct approach. The
disadvantage in speed increases as the dimensions of the matrix increases.
Consider:

In[22]:= m = Array[a, {40,51}];

In[23]:= Timing[OddOnly //@ m][[1]]

Out[23]= 1.14 Second

In[24]:= Timing[altrowcol[m]][[1]]

Out[24]= 0.02 Second

In[25]:= altrowcol[m]==(OddOnly //@ m)

Out[25]= True

Now a matrix m with larger dimensions:

In[27]:= m = Array[a, {75, 87}];

In[28]:= Timing[OddOnly //@ m][[1]]

Out[28]= 4.27 Second

In[29]:=  Timing[altrowcol[m]][[1]]

Out[29]= 0.04 Second

In[30]:= altrowcol[m]==(OddOnly //@ m)

Out[30]= True

___________________________________________________________________________________
Levent Kitis           lk3a at cars.mech.virginia.edu    lk3a at kelvin.seas.virginia.edu
University of Virginia  Department of Mechanical, Aerospace and Nuclear Engineering
___________________________________________________________________________________

• Prev by Date: Re: Re(best answer)
• Next by Date: Re: Change of variable in ODE's
• Previous by thread: Re: how to pick out alternating columns and rows in a matrix?
• Next by thread: (-1)^(3/4) -> (-1+I)/Sqrt[2]