0

The following is a really simplified version of what I'm trying to do. I have a variable fn defined in terms some other variable x. I then want to define a function of x through the variable fn.

fn = x^2;
f[x_] := fn
f[2]

However, Mathematica doesn't like it. For f[2] it just spits out $x^2$. How can I make this work? (In my complicated case I really don't want to define a function fn[x_]:=x^2 and then define f[x_]:=fn[x_])

Edit: It has been suggested to use Evaluate@fn. Which indeed works. However, let me propose a different example that doesn't work:

fn = x^2 a^2;
f[x_] := NIntegrate[Evaluate@fn, {a, -1, 1}]
f[2]

(and similarly if I put Evaluate@NIntegrate instead)

Rudyard
  • 471
  • 2
  • 7

1 Answers1

2

It would be better if we know why you had things set up this way, because it looks like your fighting against the evaluation engine here, but as a workaround, you could do something like this:

(* make a legit function *)
f = Function[x, Evaluate[fn]]

(* use it in your integration function *) fInt[x_] := NIntegrate[f[x], {a, -1, 1}]

This forces the x to get replaced first when you call fInt.

lericr
  • 27,668
  • 1
  • 18
  • 64