How to define part of a Manipulate control variable definition to reduce code duplication

后端 未结 3 1623
死守一世寂寞
死守一世寂寞 2020-12-04 20:46

This is a little related to this question

Define control as variable in Mathematica

But the above question did not answer my problem, as it talks about the f

3条回答
  •  广开言路
    2020-12-04 21:01

    What about this

    Manipulate[Plot[f*g, {x, -1, 1}],
     Evaluate@
      With[{styleAndpopup = 
          Function[{st, fun}, 
             {
               Style[st], 
               PopupMenu[Dynamic[fun], {x, x^2, x^3}, ImageSize -> Tiny]
             }, 
             HoldAll]},
        Grid[{styleAndpopup["f(x)=", f], styleAndpopup["g(x)=", g]}]]]
    

    This is actually a tiny example of the code-generation at work, since if you look at the FullForm of the resulting Manipulate, you will see the same expression you originally started with. The styleAndpopup is actually not a function here, but a macro, locally defined using With.

    EDIT

    Per request of the OP - generalizing to many controls. The easiest fix is to insert Sequence@@... as Sequence @@ {First@control1[.... However, there is some extraneous stuff that can be removed as well:

    Manipulate[{x, y}, 
     Evaluate@With[{control1 = 
         Function[{var, initialValue, str, from, to, incr}, 
           Unevaluated@{{var, initialValue, str}, from, to, incr, ImageSize -> Tiny}, 
           HoldAll]}, 
       Sequence @@ {
         control1[x, 0, "x=", 0, 1, .1], 
         control1[y, 0, "y=", 0, 2, .1], 
         control1[z, 0, "z=", 0, 10, .1]}]]
    

提交回复
热议问题