1
$\begingroup$

How could I define a function that references other values?

eg

a = 2 x; b = 4 k;
f[k_, x_] := a^b
$\endgroup$

1 Answer 1

3
$\begingroup$

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).

$\endgroup$
2
  • $\begingroup$ @ Leonid Shifrin, thank you for your answer - it is not absolutely necessary for me, so I think I will take your advice & keep it all within the function definition itself (though it is rather long!) - but it is good to know that there is a way - again, many thanks for your help on this - I will have a look at the link you provided to understand better the technical aspects. $\endgroup$
    – martin
    Commented Dec 17, 2013 at 19:44
  • $\begingroup$ @martin - section 4.5 here has a nice explanation of Block. $\endgroup$ Commented Dec 17, 2013 at 20:12

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.