Re: Could this be improved?
- To: mathgroup at smc.vnet.net
- Subject: [mg21776] Re: Could this be improved?
- From: Tom Burton <tburton at brahea.com>
- Date: Thu, 27 Jan 2000 22:56:57 -0500 (EST)
- Organization: Brahea, Inc.
- References: <86mdpv$2f3@smc.vnet.net>
- Sender: owner-wri-mathgroup at wolfram.com
On 26 Jan 2000 04:12:31 -0500, in comp.soft-sys.math.mathematica you
wrote:
>I wrote the following code which works correctly. I was wondering, however,
>if there was a way of doing the same thing that had more of a Mathematica
>approach. I am new to Mathematica and am still trying to get a grasp on how
>to program effectively within the environment.
>
>myMtx[v_] := Module[
> {nCols, nRows, vPadded, c},
> nCols = Length[v];
> nRows = 2nCols - 1;
> c = ZeroMatrix[nRows, nCols];
> vPadded = PadRight[v, nRows, 0];
> For[i = 1, i <= nCols, i++,
> c[[All, i]] = vPadded;
> vPadded = RotateRight[vPadded]
> ];
> c
> ]
Here is your function on a small vector,
In[72]:= myMtx[{a, b, c}]
Out[72]= {{a, 0, 0}, {b, a, 0},
{c, b, a}, {0, c, b}, {0, 0, c}}
and on a large one.
In[70]:= Timing[y = myMtx[Range[1000]];
Out[70]= {1.562 Second, Null}
In[71]:=Dimensions[y]
Out[71]={1999, 1000}
Here is a modification that lets the NestList function do the work of
repeated rotation and accumulation of the results.
In[74]:=
myMatrix1[v_List] :=
With[{n = Length[v] - 1},
Transpose[NestList[RotateRight, PadRight[v, 2*n + 1, 0], n]]
]
In[78]:= myMatrix1[{a, b, c}]
Out[78]= {{a, 0, 0}, {b, a, 0},
{c, b, a}, {0, c, b}, {0, 0, c}}
It runs about three times faster and is far easier to read, once you get
used to NestList.
In[76]:= Timing[y = myMatrix1[Range[1000]]; ]
Out[76]={0.481 Second, Null}
In[77]:= Dimensions[y]
Out[77]= {1999, 1000}
If NestList seems a bit strange, try the Table function:
myMatrix2[v_List] :=
With[{n = Length[v] - 1},
With[{pv = PadRight[v, 2*n+1, 0]},
Transpose[Table[RotateRight[pv, j], {j,0,n}]]
]]
myMatrix2 is at least as fast and perhaps easier to read at first than
myMatrix1.
An important facet of "the Mathematica approach" is to let a function
like Table or NestList assemble a result all at once, rather than
declaring space for the result (e.g., with ZeroMatrix) and then filling
it incrementally.
Tom Burton