# Creating functions from output of other calculations

Apologies in advance if the title is vague, I'm not really sure what to call this.

I have a function (call it 'foo') that generates a largeish polynomial, and it is natural to make the variables be

x[1],x[2],x[3]


and so on, so I get a polynomial, e.g.

x[1]^2 x[2]+x[3]


Now, I'd like to store this as a function

bar[x[1]_,x[2]_,x[3]_]:=foo[whatever]


This doesn't work, of course, but if the variables were e.g.

x1,x2,x3


bar[x1_,x2_,x3_]:=foo[whatever]


and that would work. I figured some replacement rule would work, e.g.

rule={x_[i_] :> ToExpression@(ToString[x] <> ToString[i])}


which looks like it should work:

x[1]^2 x[2]+x[3]/.rule


gives output

x1^2 x2 + x3


but if I define

bar[x1_,x2_,x3_]:=foo[whatever]/.rule


then

bar[1,2,3]


outputs

x1^2 x2 + x3


instead of 5, which it should.

Obviously, there is something I don't really understand about the way Mathematica handles variable names, and what I'm trying to do to fix this is probably too naive. Is there some better way to get around this problem?

Thanks in advance for any help.

One possibility would be to create a pure function from your multivariate polynomial with indexed variables:

bar = Function[Evaluate[x[1]^2 x[2] + x[3] /. x -> Slot]]
#1^2 #2 + #3 &

bar[1, 2, 3]
5


This works for polynomials in more than one variable set ( x[n_] ... y[n_] ....)

a = y[1] x[1]^2 x[2] + x[3] + y[3]

rule = x_[i_] :> Symbol[ToString[x] <> ToString[i]]
makefun[a_] := Function[Evaluate[Cases[a, x_[i_], Infinity] /. rule], Evaluate[a /. rule]]

s = makefun[a]

s[1, 2, 3, 4, 5]
(* 54 *)

s
(* Function[{x3, x1, x2, y1, y3}, x3 + x1^2 x2 y1 + y3] *)

• @KetilTveiten It's OK! JM's solution is somewhat narrower but to the point and more compact. I like it too. Note: You can expand JM's answer pretty easily for this case should you need it. Apr 5, 2013 at 9:12