[Numpy-discussion] Arithmetic on arrays of pointers

Stéfan van der Walt stefan at sun.ac.za
Wed Apr 29 03:26:46 EDT 2009


Hi Dan

2009/4/29 Dan Goodman <dg.gmane at thesamovar.net>:
> I have a slightly strange idea for something I would like to do with
> numpy which I guess probably doesn't exist, but I may be wrong. What I
> want to do, essentially, is to have two arrays of equal size, say X and
> Y, of pointers to doubles say. Then I want to do (in C notation) *x +=
> *y for each x, y in X, Y. I'd like to write this in Python as X+=Y where
> X and Y understand that they consist of arrays of pointers to doubles
> and that it should do the arithmetic on the values pointed to. Now I can
> do this in C easily enough, and integrate it with numpy via weave or
> whatever (it only took a few lines using scipy.weave.inline), but it
> would be really nice if something along these lines were already in
> numpy or an extension of it already. Anyone know of anything like that
> or had any experience with similar situations?

That's an interesting idea; I'm just glad I don't have to deal with
all those segfaults :-)

If you are not concerned about speed, you can define an array of
objects, and tell those objects how to handle the different
operations.  But, since you are doing simulations, I guess you want it
to be fast, so I would look at defining a "pointer" data-type.  All
this is much more work than simply writing the loop in Cython or
ctypes, though!

I wonder if it wouldn't be safer to abstract your "pointers" to an
object that is less hazardous to use, say a list.  Then you have

slots = [obj1, obj2, obj3, ..., obj10]
links = array([slots[0], slots[6], slots[20]], dtype=object) # at
least this won't segfault
links = array([slots[0], slots[1], slots[3]], dtype=object) # and this
should work fine

Regards
Stéfan



More information about the NumPy-Discussion mailing list