开发者

Dynamic as a function argument

Mathematica provides many functions which are capable of handling Dynamic as an argument. For example, the function FileNameSetter has the following variant:

FileNameSetter[Dynamic[name]] 
 uses the dynamically updated current value of name, with the 
 value of name being reset if a different file is chosen.

I wonder how one goes about defining a function pattern that takes a dynamic expression as an argument. For example, here is one attempt to wrap the dynamic variant of the function LocatorPane:

SinLocatorPane[Dynamic[sinvalue_]] := 
 LocatorPane[Dyn开发者_如何学Goamic[x, (x = #; sinvalue = Sin[First[#]]) &], 
             Plot[Sin[x], {x, 0, 10}]]

What is the correct pattern to use for a dynamic expression argument? Are there any caveats with using the dynamic argument inside the function definition?


If you would like to write a function that updates the value of a certain variable, this is like passing a variable by reference. Standard way of achieving this in Mathematica is to use Hold* attributes on your function.

SetAttributes[SinLocatorPane, HoldFirst];
SinLocatorPane[sinvalue_] := 
 LocatorPane[Dynamic[x, (x = #; sinvalue = Sin[First[#]]) &], 
  Plot[Sin[x], {x, 0, 10}]]

Then

{Dynamic[sv], SinLocatorPane[sv]}

would work as your expected. Your code worked because Dynamic has HoldFirst attributed and this allowed your code to update variable sinvalue. Otherwise Dynamic was not really needed

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜