# Construct function from string

I'm looking for a way to build a function from an input string in a text box for use in graphics. This is the indended functionality:

DynamicModule[
{f = "x^2 + Sin[y]", x, y},
Column[{
Row[{"f(x,y)=", InputField[Dynamic[f]]}],
Row[{"f= ", Dynamic[f]}],
Plot3D[ToExpression[f][x, y], {x, 0, 1}, {y, 0, 1}]
}]
]


Notably, I'd like to support any form (not strictly c₁·x² + c₂·Sin[y]) and a variable number of arguments (though I'll need to know how many arguments when I try to plot it).

I've tried some approaches using ToExpression and Symbol with no luck. I did manage to define a function inside the inputbox, ie:

f[x_]:=x^2;     {ENTER}
f[3]            {ENTER}


↳ Modifies the inputbox to display 9, but I can't seem to extract that f[] that I defined.

I also tried to modify the code in this answer, but I still couldn't get the expression to be stored as a function like the asker requested there.

Am I missing something, or is this behavior not really possible in Mathematica?

• Quite old but seems to be about that: 26985, also related: 783
– Kuba
Commented Sep 15, 2017 at 6:08

Why do you need to use strings? What's wrong with:

DynamicModule[{f=x^2 + Sin[y]},
Column[{
Row[{"f(x,y)=", InputField[Dynamic[f]]}],
Dynamic @ Plot3D[f,{x,0,1},{y,0,1}]
}]
]

• Silly me, thinking that inputboxes had to return strings. Mathematica is magic. Commented Sep 15, 2017 at 6:31
• There are edge cases, normally f[x_] := x/x for x = 0will give Indeterminate but here x/x will give 1 for x = 0
– Kuba
Commented Sep 15, 2017 at 8:22
• @Kuba There is always InputField[Dynamic[f], Hold[Expression]], although then the Plot3D evaluation is trickier. Commented Sep 15, 2017 at 14:30
• @CarlWoll yep, I know, your solution is probably all that is needed here yet it is good to keep those issues in mind.
– Kuba
Commented Sep 15, 2017 at 14:34