I am trying to create a function that generates a tensor according to a list, each of whose elements specifies the range of the corresponding dimension of the tensor and whose length specifies the total dimension of the tensor. I tried two versions using mainly "Table" and "Splice" functions.
Version 1:
ClearAll[i]
imax = {2, 3, 4};
Table[i[n], {n, Length[imax]}]
Table[{i[n], imax[[n]]}, {n, Length[imax]}]
Table[%%, Splice[%, Table]]
which produces
{i[1], i[2], i[3]}
{{i[1], 2}, {i[2], 3}, {i[3], 4}}
Table[%%, Splice[%, Table]]
where "Splice" fails to work.
Version 2:
ClearAll[i]
imax = {2, 3, 4};
Table[i[n], {n, Length[imax]}]
Table[{i[n], imax[[n]]}, {n, Length[imax]}]
Table[%%, Splice[{{i[1], 2}, {i[2], 3}, {i[3], 4}}, Table]]
which produces
{i[1], i[2], i[3]}
{{i[1], 2}, {i[2], 3}, {i[3], 4}}
{{{{1, 1, 1}, {1, 1, 2}, {1, 1, 3}, {1, 1, 4}}, {{1, 2, 1}, {1, 2,
2}, {1, 2, 3}, {1, 2, 4}}, {{1, 3, 1}, {1, 3, 2}, {1, 3, 3}, {1,
3, 4}}}, {{{2, 1, 1}, {2, 1, 2}, {2, 1, 3}, {2, 1, 4}}, {{2, 2,
1}, {2, 2, 2}, {2, 2, 3}, {2, 2, 4}}, {{2, 3, 1}, {2, 3, 2}, {2,
3, 3}, {2, 3, 4}}}}
where "Splice" works as expected.
Questions:
- Why "Splice" does not work in the first version?
- How can I embed "Splice" properly into "Table", so that I could make a function such as
TensorByList[list_]:=Module[{tensor},...;tensor]
which creates a tensor without a need to setup the iterators, which was the case with "Table" when I want to create a high dimension tensor:
Table[{i1,i2,...},{i1,i1max},{i2,i2max},...]
Array[List, {2, 3, 4}]
. A good question should (1) present the task that needs to be accomplished, (2) input data available in copy-paste-able form, and (3) desired output. Optionally, you can provide other details. As presented, your question is asking the participants primarily to do a code review. $\endgroup$Splice
: "Splice
is resolved as part of the standard evaluation process. It is not resolved in expressions that are held or inactive. "Table
is a function withHoldAll
attribute (it does analyze its argument to some degree, though), so the behavior of version 1 is actually expected, and the standard way to fix the code is to useEvaluate
:Table[%%, Evaluate@Splice[%, Table]]
. So, the real problem is not "Why "Splice" does not work in the first version?", but "Why "Splice" works in the second version?", which I'm not sure how to answer. $\endgroup$Table
andSplice
. $\endgroup$