Re: Can model parameters be global?
- To: mathgroup at smc.vnet.net
- Subject: [mg79946] Re: Can model parameters be global?
- From: "Nasser Abbasi" <nma at 12000.org>
- Date: Thu, 9 Aug 2007 05:23:39 -0400 (EDT)
- References: <f9c1av$6it$1@smc.vnet.net>
- Reply-to: "Nasser Abbasi" <nma at 12000.org>
"Neil Stewart" <neil.stewart at warwick.ac.uk> wrote in message news:f9c1av$6it$1 at smc.vnet.net... > When implementing a mathematical model in physics or psychology, for > example, how do other people deal with model parameters in Mathematica? > Would you represent the speed of light as a global variable or a local > variable. For example, would you use > > Energy[m_]:=m*c^2 (* c is a global variable *) > > or > > Energy[m_,c_]:=m*c^2 (* c is a local variable *) > > ? > > The first seems neater. But problems arise in psychology, my domain, where > the values of model parameters are unknown and are left as free > parameters, > adjusted to best-fit the data. > > Both local and global methods work well with optimisation. For example, > > NMinimize[Energy[1],{c}] > {0., {c -> 0.}} > > and > > NMinimize[Energy[1,c],{c}] > {0., {c -> 0.}} > > But the global variable solution does not work well with Manipulate. > For example, > > Manipulate[Dynamic[Energy[1]], {c, 0, 1}, LocalizeVariables -> False] > > works, but looks a right mess and also results in c taking a value that > needs a Clear[c] before using other functions like NMinimize. On the other > hand the local variable version > > Manipulate[Energy[1, c], {c, 0, 1}] > > is nice and simple. But the local variable solution results in having to > pass all of the model parameters to the function. This is fine in this > trivial example, but becomes unwieldy when there are ten model parameters > and the model is defined using a set of functions. (A c-like struct could > help, but there does not seem to be a neat way to do this in Mathematica.) > > So what do other people do? I'd be really interested to hear. > I am no expert in Mathematica, but if I learned something about programming in Mathematica, it is never to use global variables. They make debugging code so hard. Even more in Mathematica. In Manipulate, I use this pattern: process[p1_,p2_,...]:=Module[{local variables}, do the work here] Manipulate[ process[p1,p2,....],{{p1,1,10,1},{p2,1,10,1},.etc...}] It does not matter if your Manipulate has 10 or 50 parameters as input from the GUI, pass them all to the process function and do not use globals. When your code is more than 1000 lines long, you will thank me for this ;) Nasser