1
$\begingroup$

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?

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

1 Answer 1

4
$\begingroup$

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

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.