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
[EMAIL PROTECTED]
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()

_______________________________________________
Numpy-discussion mailing list
Numpy-discussion@scipy.org
http://projects.scipy.org/mailman/listinfo/numpy-discussion

Reply via email to