2011-04-18 63 views
6

Mathematica提供了許多能夠將Dynamic作爲參數的函數。 例如,功能FileNameSetter具有以下變體:作爲函數參數的動態

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

不知如何人去有關定義函數圖案,需要一個動態表達式作爲參數。例如,這裏是一個企圖包裹功能LocatorPane的動態變形:

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

什麼是用於動態表達論點正確的模式?有沒有在函數定義中使用動態參數的警告?

+3

我認爲教程/ AdvancedManipulateFunctionality的'自定義控件外觀'部分將是相關的。不要忘記閱讀本教程頂部提到的三個先決條件。 – 2011-04-18 19:07:09

+0

感謝您提供指南的鏈接。 – sakra 2011-04-19 11:10:41

回答

4

如果你想編寫一個函數來更新某個變量的值,這就像通過引用傳遞一個變量。在Mathematica中實現此功能的標準方法是在您的函數上使用Hold*屬性。

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

然後

{Dynamic[sv], SinLocatorPane[sv]} 

將作爲您的預期。你的代碼工作,因爲動態有HoldFirst歸因於此,並允許您的代碼更新變量sinvalue。否則動態不是真的需要