Revision history[back]
2
No.1 Revision
updated2010-04-17 19:57:49
kilian's gravatar image
1

assignment to non-contiguous sub-array

What is the best way, to address a non-contiguous sub-array without using an explicit loop. I have an array, say m = np.arange(16).reshape(4,4) and I am interested in the sub-array with row/column index, say [0,1,3].

One way to address this sub-array is

    >>> import numpy as np
      >>> m = np.arange(16).reshape(4,4)
      >>> idx = [0,1,3]
      >>> m[idx][:,idx]
      
array([[ 0,  1,  3],
             [ 4,  5,  7],
             [12, 13, 15]])

15]])

However, this returns a copy of the sub-matrix and therefore can't be used to assign a value, say 0.

Do i have to use an explicit loop, such as

>>> for i in idx: m[i][:,idx] = 0
      

or is there a more elegant/faster solution?

Thanks, Kilian

1
asked2010-04-17 19:55:21
kilian's gravatar image
1

assignment to non-contiguous sub-array

What is the best way, to address a non-contiguous sub-array without using an explicit loop. I have an array, say m = np.arange(16).reshape(4,4) and I am interested in the sub-array with row/column index, say [0,1,3].

One way to address this sub-array is

    >>> import numpy as np
    >>> m = np.arange(16).reshape(4,4)
    >>> idx = [0,1,3]
    >>> m[idx][:,idx]

array([[ 0,  1,  3],
       [ 4,  5,  7],
       [12, 13, 15]])

However, this returns a copy of the sub-matrix and therefore can't be used to assign a value, say 0.

Do i have to use an explicit loop, such as

>>> for i in idx: m[i][:,idx] = 0

or is there a more elegant/faster solution?

Thanks, Kilian

Made with Django.