Hi, I would like to know how in a custom function Mathematica passes the values of the variables.
In this simple example I create a function f(T) with several tasks/lines. How can I make that tf takes the numerical value that FindMaximum is using in each iteration? I mean when I Print[tf] instead of having twait I want to assign a numerical value.
In[118]:= f[T_] :=
Module[{g, tf = T},
Print[tf];
g = Abs[(tf - 3)^2];
{g}
]
In[119]:= FindMinimum[f[twait], {twait, 5}]
During evaluation of In[119]:= twait
Out[119]= {2.61186*10^-19, {twait -> 3.}}
Return {g} only to expressions that expect a List[], Return[g] to Functions waiting for a value . The last expression of a Module is it’s Return (noting ; constitutes an empty expression in this case (or separator sometimes), quieting the return). The tf was duplicitous and also used before it had been evaluated (before a value was assigned - see Evaluate[] and tutorials), thus Print printed the Symbol[“twait”] - unevaluated expressions are composed of Symbols yet to have values, you might say.
You did not need to create a Function or Module, FindMinimum[Abs[(tw - 3)^2], {tw, 5}] will have the same output. Yes there are global variables and local variables. Mathematica handles these with Context[] which has allot to do with Begin[] End[] Package[] and making Mathematica built-ins.
FindMinimum[(Abs[(# - 3)^2]) &[tw], {tw, 5}]
Also has the same output. “Everything is an expression”.
As to your local variable tw, it disappears when the function becomes un-defined. It otherwise has a name usable from the outer context “global” by specifying it’s context. (that is advanced - ignore that until you read the advanced section of the Mathematica Book)