RE: Could this be improved?
- To: mathgroup at smc.vnet.net
- Subject: [mg21751] RE: [mg21741] Could this be improved?
- From: "Ersek, Ted R" <ErsekTR at navair.navy.mil>
- Date: Thu, 27 Jan 2000 22:56:33 -0500 (EST)
- Sender: owner-wri-mathgroup at wolfram.com
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]
];
c
]
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.
In[1]:=
Partition[{0,0,3,2,1,0,0}, 3,1]
Out[1]=
{{0,0,3},{0,3,2},{3,2,1},{2,1,0},{1,0,0}}
In[2]:=
Reverse[%]
Out[2]=
{{1,0,0},{2,1,0},{3,2,1},{0,3,2},{0,0,3}}
The output above is what you want. A definition for myMtrx that does this is
given below.
In[3]:=
myMtx[v_?VectorQ]:=With[{pad=Table[0,{Length[v]-1}]},
Reverse[Partition[Join[pad,Reverse[v],pad],3,1]]
]
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.
--------------------
Regards,
Ted Ersek
On 12-18-99 Mathematica tips, tricks at
http://www.dot.net.au/~elisha/ersek/Tricks.html
had a major update