Mathematica Stack Exchange is a question and answer site for users of Mathematica. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

How could I define a function that references other values?


a = 2 x; b = 4 k;
f[k_, x_] := a^b
share|improve this question
up vote 3 down vote accepted

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

share|improve this answer
@ 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. – martin Dec 17 '13 at 19:44
@martin - section 4.5 here has a nice explanation of Block. – Chris Degnen Dec 17 '13 at 20:12

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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