How could I define a function that references other values?
eg
a = 2 x; b = 4 k;
f[k_, x_] := a^b
For reasons explained here, I would strongly advise against using this kind of constructs, which in essence use global variables. However, if you must do this, here is one easy way:
ClearAll[a, b, x, k, f];
a = 2 x; b = 4 k;
f[k_, x_] = a^b
that is, use Set
instead of SetDelayed
- in which case your r.h.s. will be computed at the time of the assignment.
Here is another method, which might be somewhat safer:
ClearAll[a, b, x, k, f];
a = 2 x; b = 4 k;
f[kk_, xx_] := Block[{x = xx, k = kk}, a^b]
that is, use Block
to dynamically localize x
and k
, then call your code (a^b
here).
But again, the best (safest) way is to make all functions (a
and b
here) explicitly take the parameters, and pass the parameters explicitly (as explained in the link I gave).
Block
.
$\endgroup$
Commented
Dec 17, 2013 at 20:12