Using ufunc.at on a matrix

Suppose I have the following numpy array:

>>> a=np.zeros(10)
>>> a
array([ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.])

I can use numpy.ufunc.at to change this array:

>>> np.add.at(a, [0,3], 2)
>>> a
array([ 2.,  0.,  0.,  2.,  0.,  0.,  0.,  0.,  0.,  0.])

If I try to use a matrix now, then I assume that this method does not work:

>>> m=np.zeros(16).reshape(4,4)
>>> m
array([[ 0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.]])
>>> np.add.at(m, [(0,0),(1,1)], 2)
>>> m
array([[ 0.,  4.,  0.,  0.],
       [ 0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.]])

My expectation based on supplying a list of tuples [(0,0),(1,1)]would be:

      [[ 2.,  0.,  0.,  0.],
       [ 0.,  2.,  0.,  0.],
       [ 0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.]]

Any suggestions on what I'm using as a list of indexes in numpy.ufunc.atto get this matrix?

+4
source share
1 answer

If you want to do multi-dimensional indexing, you do not pass a list of index tuples; you pass a tuple of index lists (or arrays of indexes).

indices = ([0, 1], [0, 1])
np.add.at(m, indices, 2)

indices[0] , , indices[1] . :

In [10]: a = numpy.zeros([4, 4])
In [11]: a
Out[11]: 
array([[ 0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.]])
In [12]: indices = ([0, 3], [2, 1])
In [13]: numpy.add.at(a, indices, 2)
In [14]: a
Out[14]: 
array([[ 0.,  0.,  2.,  0.],
       [ 0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.],
       [ 0.,  2.,  0.,  0.]])

, . , , , , , .

+7

All Articles