1
$\begingroup$

I have a family of functions, each of which takes a long time to build the expression. Once the functional form is determined, however, calculations are very fast. So I want to build a table of functions programatically. Something like:

exprList = Table[buildExpr[a, b, x], {a, 1, 5}, {b, 1, 100}]
exprFunc[a_, b_, x_] := Evaluate[exprList[[a, b]]]

However, the above throws a Part error, saying I can't use a and b in Part in a function. I've tried various other things from related questions on the internet, but still no luck.

$\endgroup$

2 Answers 2

3
$\begingroup$

You can use:

exprFunc[a_, b_, x_] = Indexed[exprList, {a, b}];

Then:

exprFunc[1, 5, z]

buildExpr[1, 5, z]

$\endgroup$
2
$\begingroup$

There is more than one way to do things in Mathematica. A simple example code

buildExpr[a_, b_, v_] := a + b v;
ClearAll[x]; (* clears values associated with 'x' *)
exprList = Table[buildExpr[a, b, x], {a, 3}, {b, 3}];
exprFunc[a_, b_, v_] := Block[{x = v}, exprList[[a, b]]];
exprFunc[1, 2, u] == 1 + 2 u

returns True. The initial problem you encountered was the Evaluate[exprList[[a, b]]] which was being evaluated in defining the exprFunc but a and b were not defined yet. You want to avoid using Evaluate and use Block instead to give a local value of the variable x which will be used by the expressions in exprList. The documentation for Evaluate shows that it is only needed for some special cases to override Holds.

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.