Applying a function to a 2-D numarray

Robert Kern rkern at ucsd.edu
Mon May 16 23:06:53 EDT 2005


Matt Feinstein wrote:
> On Mon, 16 May 2005 12:03:24 -0600, Steven Bethard
> <steven.bethard at gmail.com> wrote:
> 
>>Can you give an example of what you really want to do?  Probably there 
>>are numarray functions that you can use.  In general, you'll do better 
>>applying a sequence of numarray functions than operating element-wise on 
>>an array and converting it from a list back to an array...
> 
> Well, for example, suppose I want to modify the elements of the matrix
> in some fashion. However, I'm not entirely sure how I want to do it.
> As a strawman, I generate a function with a Boolean test in it that
> multiplies by one factor if the matrix element is in an interval and
> by a different factor if it is outside the interval

As Steven Bethard suggests, using the ufuncs provided to express the 
function in a vectorial way is always the best option *if* it's possible.

Otherwise, you may want to look at Scipy's vectorize() function. I don't 
think the numarray port is quite working yet, so you may have to use 
Numeric. You will still have the same function call overhead since you 
will be calling the Python function for each element, but the loops will 
be in C.

Type:             classobj
String Form:   scipy_base.function_base.vectorize
Namespace:        Interactive
File: 
/Library/Frameworks/Python.framework/Versions/2.4/lib/python2.4/site-packages/scipy_base/function_base.py
Docstring:
   vectorize(somefunction)  Generalized Function class.
Description:
   Define a vectorized function which takes nested sequence objects or 
numerix arrays as inputs and returns a numerix array as output, 
evaluating the function over successive tuples of the input arrays like 
the python map function except it uses the broadcasting rules of numerix 
Python.

Input:
     somefunction -- a Python function or method

Example:

   def myfunc(a,b):
       if a > b:
           return a-b
       else:
           return a+b
   vfunc = vectorize(myfunc)

   >>> vfunc([1,2,3,4],2)
   array([3,4,1,2])

-- 
Robert Kern
rkern at ucsd.edu

"In the fields of hell where the grass grows high
  Are the graves of dreams allowed to die."
   -- Richard Harter




More information about the Python-list mailing list