[Numpy-discussion] fiddling the strides of an array

A. M. Archibald peridot.faceted at gmail.com
Sun Nov 19 14:42:03 CST 2006


I have a function that would like to be able to take an array, look at
its 'strides' and 'shape' tuples, and fabricate another array that is
similar to the first but has the adjusted values.

For a simple example:

def fiddle(a):
    strides = list(a.strides)
    shape = list(a.shape)
    return N.ndarray.__new__(N.ndarray, strides=strides, shape=shape,
buffer=a, dtype=a.dtype)

Unfortunately, this has a few problems.

* It always makes ndarrays, even if the original was some subtype.
(not a big deal for me, but still a bit annoying)

* It fails unnecessarily if the array is not "contiguous": for
example, fiddle(N.zeros((2,2,2,2)).swapaxes(0,2)) fails, saying
"expected a single-segment buffer object".

This second problem is my real problem. Is there a way I can tell
numpy "no really, I know what I'm doing with these strides, use the
same underlying memory as this array"? (Of course I can flatten the
array, but that will copy it unnecessarily.)

A. M. Archibald

More information about the Numpy-discussion mailing list