Numarray: Using sum() within functions

Christopher T King squirrel at WPI.EDU
Mon Aug 16 13:53:30 EDT 2004


On Sat, 14 Aug 2004, Jim Cser wrote:

> I have a function to generate a multi-dimensional array, which then
> gets summed over one axis.  The problem is that the dimensions
> are large, and I run out of memory when I create the entire array,
> so I'm trying to do the sum *within* the function.
> 
> Example-- variables x,y,z,t; dimensions numX, numY, numZ, numT;
> functions f1(x,y,z,t), f2(y,z,t);  want to calculate f1*f2 and
> sum over t to get out[x,y,z].

Would something like the following work?

 def f3(x, y, z, t=arange(numT)):
     return sum(f1(x,y,z,t)*f2(y,z,t))

This assumes that f1() and f2() can operate on array objects.  If not, the 
following (much slower) method should work:

 def f3(x, y, z):
     return sum(fromfunction(lambda t: f1(x,y,z,t)*f2(y,z,t),(numT,)))

To make the output matrix, you could use either this:

 out = fromfunction(f3, (numX, numY, numZ))

which will save memory, but will be slow, or (assuming f1 and f2 support 
arrays):

 out = f3(arange(numX), arange(numY), arange(numZ))

which will eat lots of memory (more that you say you have, if you use the
first f3()), but will be very fast.

Hope this helps.




More information about the Python-list mailing list