Take the 2-minute tour ×
Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

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

etc. instead, I could do

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.

share|improve this question

2 Answers 2

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

s
(* 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. –  belisarius Apr 5 '13 at 9:12

Your Answer

 
discard

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.