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


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


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


etc. instead, I could do


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





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.


2 Answers 2


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]

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

(* Function[{x3, x1, x2, y1, y3}, x3 + x1^2 x2 y1 + y3] *)
  • $\begingroup$ @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. $\endgroup$ Commented Apr 5, 2013 at 9: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.