[Numpy-discussion] question about optimizing
Brian Blais
bblais@bryant....
Fri May 16 19:34:08 CDT 2008
Hello,
I have a custom array, which contains custom objects (I give a
stripped down example below), and I want to loop over all of the
elements of the array and call a method of the object. I can do it
like:
a=MyArray((5,5),MyObject,10)
for obj in a.flat:
obj.update()
but I was wondering if there is a faster way, especially if
obj.update is a cython-ed function. I was thinking something like
apply_along_axis, but without having an input array at all.
Is there a better way to do this? While I'm asking, is there a
better way to overload ndarray than what I am doing below? I tried
to follow code I found online, but the examples of this are few and
far between.
thanks you for any help!
Brian Blais
--
Brian Blais
bblais@bryant.edu
http://web.bryant.edu/~bblais
from numpy import ndarray,prod,array
class MyObject(object):
def __init__(self,value):
self.value=value
def update(self):
self.value*=2
def __repr__(self):
return "My value is %d." % self.value
class MyArray(ndarray):
def __new__(subtype, shape,obj, *args,**kwargs):
if isinstance(shape,int):
N=shape
shape=(shape,)
else:
N=prod(shape)
objs=[]
for i in range(N):
objs.append(obj(*args,**kwargs))
arr = array(objs, dtype=None, copy=False)
arr = arr.view(subtype)
arr.shape=shape
return arr
if __name__=="__main__":
a=MyArray((5,5),MyObject,10)
for obj in a.flat:
obj.update()
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://projects.scipy.org/pipermail/numpy-discussion/attachments/20080516/25bbad67/attachment.html
More information about the Numpy-discussion
mailing list