a question about numpy

sturlamolden sturlamolden at yahoo.no
Wed Sep 9 05:03:56 CEST 2009

On 9 Sep, 03:45, hi_roger <rechardc... at gmail.com> wrote:

> i know how to select a submatrix using the slice object in numpy. But
> how can i select a submatrix
> A[i1,i2,i3;j1,j2,j3] (elements in A on line i1,i2,i3 and column
> j1,j2,j3 ,  and i1,i2,i3,j1,j2,j3 are all arbitrary numbers )

You just pass an array of ints for each dimension. If you want a 3x3
submatrix, you must pass in two 3x3 arrays of indices.

> The submatrix must share data memory with original matrix.

That is the tricky part. An ndarray must be indexable using an array
of strides. That is in C:

void *get_element_ptr( PyArrayObject *a, int indices[])
   char *out = a->data;
   int d;
   for (d=0; d < a->nd; d++)
      out += indices[d] * a->strides[d];
   return (void *)out;

If you slice with an array or list of ints in Python, the resulting
array cannot be indexed like this. Therefore NumPy is forced to make a
copy. So if I do

>>> import numpy as np
>>> a = np.zeros((10,10))
>>> b = a[[1,3,5],[6,7,8]]

I get this:

>>> b.flags['OWNDATA']


>>> c = a[::2,::2]
>>> c.flags['OWNDATA']

This is because C can still be indexed with strides as shown above,
and no copy is made.

More information about the Python-list mailing list