[Numpy-discussion] Logical indexing and higher-dimensional arrays.

Sturla Molden sturla@molden...
Wed Feb 8 12:20:25 CST 2012


On 08.02.2012 18:17, josef.pktd@gmail.com wrote:

> I think I use it quite a bit, and I like that the broadcasting in
> indexing is as flexible as the broadcasting of numpy arrays
> themselves.
>
> x[np.arange(len(x)), np.arange(len(x))]  gives the diagonal for example.


Personally I would prefer that a function like np.diag could return a 
view. (The stride is regular, so why not?)

def diag(x):
    return x.reshape(np.prod(x.shape))[::x.shape[0]+1]

 >>> a = np.zeros((10,10))
 >>> d = diag(a)
 >>> d[:] = 2
 >>> a
array([[ 2.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.],
        [ 0.,  2.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.],
        [ 0.,  0.,  2.,  0.,  0.,  0.,  0.,  0.,  0.,  0.],
        [ 0.,  0.,  0.,  2.,  0.,  0.,  0.,  0.,  0.,  0.],
        [ 0.,  0.,  0.,  0.,  2.,  0.,  0.,  0.,  0.,  0.],
        [ 0.,  0.,  0.,  0.,  0.,  2.,  0.,  0.,  0.,  0.],
        [ 0.,  0.,  0.,  0.,  0.,  0.,  2.,  0.,  0.,  0.],
        [ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  2.,  0.,  0.],
        [ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  2.,  0.],
        [ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  2.]])

Sturla


More information about the NumPy-Discussion mailing list