There are two easy approaches that come to mind. The first is to simply use MapThread
.
MapThread[foo, {Range[0, 4], Range[24, 32, 2]}]
{foo[0, 24], foo[1, 26], foo[2, 28], foo[3, 30], foo[4, 32]}
If you are collecting all results this is probably a perfectly good approach as memory is unlikely to be a problem.
The second is to define the relationship between the two iterators and then use only one. For the example above the second iterator can be generated from the first with the formula 2 (# + 12)
. We could then write:
Table[foo[i, 2 (i + 12)], {i, 0, 4}]
{foo[0, 24], foo[1, 26], foo[2, 28], foo[3, 30], foo[4, 32]}
I suppose you would like a syntax more like Table
. The question is then how to automate this.
For MapThread
I propose:
SetAttributes[pTable1, HoldAll]
pTable1[expr_, iter : {_Symbol, __} ..] :=
MapIndexed[Set, Hold[iter][[All, 1]]] /. List -> Slot /. _[x__] :>
MapThread[
Block[{x}, expr] &,
Range @@@ Rest /@ {iter}
]
Now:
pTable1[foo[x, y], {x, 0, 4}, {y, 24, 32, 2}]
{foo[0, 24], foo[1, 26], foo[2, 28], foo[3, 30], foo[4, 32]}
While working on the second method it occurred to me that a different syntax is superior. Ranges should instead be given as a starting value and a step size rather than start,end,step, then a single repetition value for all iterators should be given. This both shortens syntax and assures agreement of length.
SetAttributes[pTable2, HoldAll]
pTable2[expr_, iter : {_Symbol, __} .., n_Integer] :=
Module[{Z},
Hold[iter] /. {i_, a_, s_: 1} :> (i = a - s + s Z) /. _[x__] :>
Block[{x}, Table[expr, {Z, n}]]
]
Example use:
pTable2[foo[x, y], {x, 0}, {y, 24, 2}, 5]
{foo[0, 24], foo[1, 26], foo[2, 28], foo[3, 30], foo[4, 32]}
We can prettify either function by adding syntax highlighting similar to Table
, indicating the scoped Symbols in the iterators:
SyntaxInformation[pTable2] = SyntaxInformation[Table];
Now input appears as:

As indicated x
and y
are correctly scoped, and evaluation is as in Table
:
x = y = "Fail!";
bar := foo[x, y];
pTable2[bar, {x, 0}, {y, 24, 2}, 5]
{foo[0, 24], foo[1, 26], foo[2, 28], foo[3, 30], foo[4, 32]}
Table
which increments bothi
andr
at the same time, so i and r are always equal. Can you tell me only one example where you can create a list with those two iterators which you cannot create with a single iterator? Otherwise, I won't understand what you try to do. $\endgroup$ – halirutan♦ Jul 23 '14 at 10:36Range[0, 5]^2
$\endgroup$ – eldo Jul 23 '14 at 10:38Table
so to have many,Table
increases the x already. But also I need to have an iterator to add a few degrees to have firing order, which will follow a few number such as 1,3,4,2. So the iterators must follow 0->2 Pi, and 1,3,4,2 $\endgroup$ – ptolemy0 Jul 23 '14 at 10:45cyl=8;Table[{i,(i-1)*2Pi/(cyl)},{i,cyl}]
? $\endgroup$ – halirutan♦ Jul 23 '14 at 11:15