[Numpy-discussion] Array of Callables
Michael McLay
mclay@l2sg....
Wed Mar 21 09:53:36 CDT 2007
On Wednesday 21 March 2007 09:52, Andrew Corrigan wrote:
> Anne Archibald <peridot.faceted <at> gmail.com> writes:
> > Vectorizing apply is what you're looking for, by the sound of it:
> > In [13]: a = array([lambda x: x**2, lambda x: x**3])
> >
> > In [14]: b = arange(5)
> >
> > In [15]: va = vectorize(lambda f, x: f(x))
> >
> > In [16]: va(a[:,newaxis],b[newaxis,:])
> > Out[16]:
> > array([[ 0, 1, 4, 9, 16],
> > [ 0, 1, 8, 27, 64]])
>
> Thanks for pointing that out. Technically that works, but it doesn't
> really express this operation as concisely and as naturally as I'd like to
> be able to.
>
> What I really want is to be able to write:
> >>> a = array([lambda x: x**2, lambda x: x**3])
> >>> b = arange(5)
> >>> a(b)
>
> and get:
> array([[ 0, 1, 4, 9, 16],
> [ 0, 1, 8, 27, 64]])
>
> instead of the present error message:
> Traceback (most recent call last):
> File "<stdin>", line 1, in ?
> TypeError: 'numpy.ndarray' object is not callable
You could create a class with a __call__ method like the following.
from numpy import arange, array,vectorize,newaxis
class VA:
def __init__(self,arg):
self.a = array(arg)
def __call__(self,b):
va = vectorize(lambda f, x: f(x))
return va(self.a[:,newaxis],b[newaxis,:])
a = VA([lambda x: x**2, lambda x: x**3])
b = arange(5)
print a(b)
More information about the Numpy-discussion
mailing list