The problem:
I want to define a function tab
to replace the long line
Table[f[i,j,k,l],{i,3},{j,3},{k,3},{l,3}]
by a shorter line
tab[f[i,j,k,l],i,j,k,l]
Then I need to declare i,j,k,l
in tab
to be local variables, just like in Table
.
My trial:
tab[f_, jlist__] := Module[{jlist2 = {jlist}, jlist3},
jlist3 = Sequence @@ ({#1, 3} & ) /@ jlist2;
Table[f, Evaluate[jlist3]]]
Then I succeeded in
(*Input := *) tab[h[i, j], i, j]
(*Output:= {{h[1, 1], h[1, 2], h[1, 3]}, {h[2, 1], h[2, 2], h[2, 3]}, {h[3, 1], h[3, 2], h[3, 3]}}*)
whose output is the same as from Table[h[i,j],{i,3},{j,3}]
. But I failed in
(*Input := *) tab[(f[i, j] = g[i, j]), i, j]
(* {{g[1, 1], g[1, 2], g[1, 3]}, {g[2, 1], g[2, 2], g[2, 3]}, {g[3, 1], g[3, 2], g[3, 3]}} *)
in which f[i,j]=g[i,j]
is evaluated first. I wanted it to behave as Table[f[i,j]=g[i,j],{i,3},{j,3}]
.
Update: Below rcollyer's answer leads to the correct output by using SetAttributes[tab,HoldAll]
first. However, I still want to know if I can declare i
and j
as local variables. So far they are not local variables and I would have errors like:
(*Input :=*) i=3; tab[f[i],i]
(* Error message "Table::itraw: Raw object 3 cannot be used as an iterator. >>"
Output:= Table[f[i], {3, {0, 1, 2, 3}}] *)
Can anyone solve this?