Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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[Dynamic[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?

like image 832
sakra Avatar asked Apr 18 '11 18:04

sakra


1 Answers

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

like image 200
Sasha Avatar answered Oct 04 '22 01:10

Sasha