Re: Calculate the first time, not each time (?)
- To: mathgroup at smc.vnet.net
- Subject: [mg94576] Re: Calculate the first time, not each time (?)
- From: Jean-Marc Gulliet <jeanmarc.gulliet at gmail.com>
- Date: Tue, 16 Dec 2008 06:04:28 -0500 (EST)
- Organization: The Open University, Milton Keynes, UK
- References: <gi7ljg$cui$1@smc.vnet.net>
Michael Young wrote: > Hello, > > I'm doing some engineering which will involve a large number of points > -- and I anticipate time problems if all steps are repeated for each > one. Here's an outline of the way I'd like to approach it. > > shapeprimativeXvalues := N[Table[functionpX[v], {v, vlimit}]] > shapeprimativeYvalues := N[Table[functionpY[v], {v, vlimit}]] > > Arriving at these will involve some calculation, and once the results > are in, it is unnecessary that the this be repeated when the values > are used. > > adaptshapetoitslocation[v_] := (various operations on or including) > shapeprimativeXvalues[[v]] (and or) shapeprimativeYvalues[[v]] > > Is there a way I can instruct Mathematica to evaluate a table, (value > or function), once, when it is first called; then not to evaluate it > again, but to pass numerical results on request? Hi Michael, The following example outlines a possible approach to what I think you want to achieve, though I do not like this implementation since it uses (too) many *global* variables. t := If[Length[tvals] == 0, tvals = N[Table[f[v], {v, vlimit}]], tvals] So, the function t is evaluated every time it is called (thanks to the operator SetDelayed ':=') but it checks if the global array tvals already holds some values (i.e. if the array length is not zero). If the array is empty, values are computed, stored in tvals, and returned to the caller. If the array holds previous values, these values are directly returned to the caller. Below is a fully working example. Clear[f, g, t] f[x_] := Sin[x] RandomInteger[] t := If[Length[tvals] == 0, Print["To Be Computed..."]; tvals = N[Table[f[v], {v, vlimit}]], Print["Already Computed"]; tvals] vlimit = 2 Pi; tvals =.; g[v_] := Module[{x}, t; Print[t]; x = t[[v]]; Print[x]] g[2] To Be Computed... Already Computed {0.,0.,0.14112,0.,0.,0.} Already Computed 0. g[3] Already Computed Already Computed {0.,0.,0.14112,0.,0.,0.} Already Computed 0.14112 Hope this helps, -- Jean-Marc