A direct replacement
Perhaps your specific example might best be handled with:
Array[
(a[##] = f[##]) &,
Table[4, {3}]
]
{ . . . { . . . {f[3, 1, 1], f[3, 1, 2], f[3, 1, 3], f[3, 1, 4]} . . . } . . . }
Where 4
is n and 3
is the number of loops.
Output it was included above for illustration; it may be suppressed with CompoundExpression
:
Array[
a[##] = f[##]; &,
Table[4, {3}]
];
Note its placement both in the Function
and after the Array
; for former is for memory conservation.
A better alternative?
While the method above may be considered as a fairly direct replacement for your code if it is representative of the operation you are performing it would be better just to keep a table of values and extract the parts by index.
f = Multinomial;
farray = Outer[f, ##] & @@ Table[Range@9, {3}];
farray[[7, 9, 4]]
f[7, 9, 4]
55426800
55426800
This format will be more memory efficient than the DownValues
(hash-table) produced by assignments to a
.
Timings
rcollyer asked for timings. In version 7:
n = 9; args = 6;
f = Multinomial;
Array[(a[##] = f[##]); &, Table[n, {args}]]; // AbsoluteTiming
farray = Outer[f, ##] & @@ Table[Range@n, {args}]; // AbsoluteTiming
{2.4011374, Null}
{0.7990457, Null}
n=3; a = Table[f[x1, x2, x3], {x1, n}, {x2, n}, {x3, n}]
? $\endgroup$For
loops there. I know I am against deleting this answer, but I am still a bit fuzzy on closing questions :). $\endgroup$