Message Boards Message Boards

1 Reply
1 Total Likes
View groups...
Share this post:

Remembering values for reuse

Posted 10 years ago
I wish to clarify an aspect which I find interesting and potentially useful.

If I define a function in the following manner:
f[x_] := f[x] = (*What the function does*)
and then I evaluate the function at "a", does this mean that later it will treat f(a) as a constant?

If so, theoretically it shouldn't increase my computation time, if let's say I implement a For loop where for different ranges I use f(a), f(b), f(c),.. , compared to when I use instead upfront defined variables (A=f(a), B=f(b), C=f(c),..), right?

Or this feature is only useful for recursions?
POSTED BY: Sandu Ursu
Hello Sandu,

This is a very useful feature---and not just for recursion.

You can change the value the f later. For example
func[x_] := func[x] = Date[]

func[now] = Date[]

I find this method useful to build up indexed lists when I don't know the size of a list a priori. For a simple (not particularly useful) example which illustrates trading memory for speed.
 n = 300; m = 500; icount = 0;
 image = Table[pixel[++icount] = RandomReal[]; 
   valueLocation[pixel[icount]] = {i, j}; 
   pixel[icount], {i, 1, n}, {j, 1, m}]
theTargetPix = image[[137, 314]]

posTime = Timing[Do[Position[image, theTargetPix], {100}]]
idxTime = Timing[Do[valueLocation[theTargetPix], {100}]]
First[posTime]/First[idxTime]  (*I get around 10^4*)

POSTED BY: W. Craig Carter
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
or Discard

Group Abstract Group Abstract