I'd like to apply a set of rules to an expression defining the iterators of the table, like this:
ExampleParameters = {x0 -> 0, xp -> 1}
Table[x,{x, x0 - 3*xp, x0 + 3*xp, xp} /. ExampleParameters]
The kernel returns the following error:
Table::itform: Argument {x, x0 - 3 xp, x0 + 3 xp, xp} /. ExampleParameters
at position 2 does not have the correct form for an iterator.
Any ideas on how to generalize the table expression? Explicitly using
Table[x,ReplaceAll{x, x0-3*xp, x0+3*xp, xp}, ExampleParameters]]
leads to the same error.
Answer
Mathematica throws the error because Table
has the HoldAll
attribute which prevents the replacement from being performed before Table
sees the iterator. You can force evaluation using Evaluate
:
Table[x, Evaluate[{x, x0 - 3*xp, x0 + 3*xp, xp} /. exampleParams]]
Alternatively, instead of ReplaceAll
, use With
:
With[{x0 = 0, xp = 1}, Table[x, {x, x0 - 3*xp, x0 + 3*xp, xp}]]
In similar situations I like to use a custom-defined With
-like function that can take parameter lists. I described this function here and I'm going to reproduce it in this answer as well for completeness:
ClearAll[withRules]
SetAttributes[withRules, HoldAll]
withRules[rules_, expr_] :=
First@PreemptProtect@Internal`InheritedBlock[
{Rule, RuleDelayed},
SetAttributes[{Rule, RuleDelayed}, HoldFirst];
Hold[expr] /. rules
]
withRules[exampleParams, Table[x, {x, x0 - 3*xp, x0 + 3*xp, xp}]]
Comments
Post a Comment