       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 = Length[v];
>    nRows = 2nCols - 1;
>    c = ZeroMatrix[nRows, nCols];
>    For[i = 1, i <= nCols, i++,
>      ];
>    c
>    ]

Here is your function on a small vector,

In:= myMtx[{a, b, c}]
Out= {{a, 0, 0}, {b, a, 0},
{c, b, a}, {0, c, b}, {0, 0, c}}

and on a large one.

In:= Timing[y = myMtx[Range];
Out= {1.562 Second, Null}

In:=Dimensions[y]
Out={1999, 1000}

Here is a modification that lets the NestList function do the work of
repeated rotation and accumulation of the results.

In:=
myMatrix1[v_List] :=
With[{n = Length[v] - 1},
Transpose[NestList[RotateRight, PadRight[v, 2*n + 1, 0], n]]
]

In:= myMatrix1[{a, b, c}]
Out= {{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:= Timing[y = myMatrix1[Range]; ]
Out={0.481 Second, Null}

In:= Dimensions[y]
Out= {1999, 1000}

If NestList seems a bit strange, try the Table function:

myMatrix2[v_List] :=
With[{n = Length[v] - 1},
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

```

• Prev by Date: Re: Cursor bug in mathematica 3
• Next by Date: Re: Making a function dynamically define another conditional function...
• Previous by thread: Re: Could this be improved?
• Next by thread: RE: Could this be improved?