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

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.

share|improve this question
up vote 3 down vote accepted

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]
share|improve this answer

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] *)
share|improve this answer
I'd accept this answer too, if I could accept more than one. – Ketil Tveiten Apr 5 '13 at 8:42
@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. – Dr. belisarius Apr 5 '13 at 9: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.