MathGroup Archive 2000

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

Search the Archive

RE: Could this be improved?

  • To: mathgroup at
  • Subject: [mg21751] RE: [mg21741] Could this be improved?
  • From: "Ersek, Ted R" <ErsekTR at>
  • Date: Thu, 27 Jan 2000 22:56:33 -0500 (EST)
  • Sender: owner-wri-mathgroup at

Jordan Rosenthal  says:
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]

For example, myMtx[{1,2,3}] takes the vector {1,2,3} and turns it into the
matrix {{1, 0, 0}, {2, 1, 0}, {3, 2, 1}, {0, 3, 2}, {0, 0, 3}}


Partition is very helpful here (see the next line).  You should check the
documentation on Partition and do some experiments with it.

Partition[{0,0,3,2,1,0,0}, 3,1]


The output above is what you want. A definition for myMtrx that does this is
given below.


Mathematica has a number of built in functions to perform useful tasks. Lots
of these functions can be used in many different ways. In Version 4
Partition can be used in a great variety of ways! Using functions like
Partition can make your programs much simpler and more efficient.

Other functions you should learn about are:
Take, Drop, Select, Cases, Position, DeleteCases, Insert, ReplacePart,
Split, Thread, Flatten, FlattenAt, Inner, Outer, Map, MapAt, MapThread,
MapIndexed, Transpose, Apply, Nest, FixedPoint, Range.  Several of these
functions are explained and demonstrated on my website (see URL below).

You should also purchase a copy of Power Programming with Mathematica the
Kernel, by David B. Wagner (ISBN 0-07-912237-X). This book goes a long way
towards making you a good Mathematica programmer. 

Ted Ersek

On 12-18-99 Mathematica tips, tricks at
had a major update

  • Prev by Date: Re: Making a function dynamically define another conditional function...
  • 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?