1

I want to take the row sums of one array and place the output into the diagonals of another array. For performance reasons, I want to use the out argument of the np.sum function.

mat1 = np.array([[0.5, 0.5],[0.6, 0.4]])

mat2 = np.zeros([2,2])

mat3 = np.zeros([2,2])

If I want to place the row sums of mat1 into the first row of mat2, I can do it like this:

np.sum(mat1, axis=1, out = mat2[0])

mat2
#array([[ 1.,  1.],
#       [ 0.,  0.]])

However, if I want to place the sums into the diagonal indices of mat3, I can't seem to do so.

np.sum(mat1, axis=1, out = mat3[np.diag_indices(2)])

mat3
#array([[ 0.,  0.],
#       [ 0.,  0.]])

Of course, the following works, but I would like to use the out argument of np.sum

mat3[np.diag_indices(2)] = np.sum(mat1, axis=1)

mat3 
#array([[ 1.,  0.],
#       [ 0.,  1.]])

Can someone explain this behavior of the out argument not accepting the diagonal indices of an array as a valid output?

1 Answer 1

2

NumPy has two types of indexing: basic indexing and advanced indexing.

Basic indexing is what happens when your index expression uses only integers, slices, ..., and None (a.k.a. np.newaxis). This can be implemented entirely through simple manipulation of offsets and strides, so when basic indexing returns an array, the resulting array is always a view of the original data. Writing to the view writes to the original array.

When you index with an array, as in mat3[np.diag_indices(2)], you get advanced indexing. Advanced indexing cannot be done in a way that returns a view of the original data; it always copies data from the original array. That means that when you try to use the copy as an out parameter:

np.sum(mat1, axis=1, out = mat3[np.diag_indices(2)])

The data is placed into the copy, but the original array is unaffected.


We were supposed to have the ability to use np.diagonal for this by now, but even though the documentation says np.diagonal's output is writeable in NumPy 1.10, the relevant feature for making it writable is still in limbo. It's probably best to just not use the out parameter for this:

mat3[np.diag_indices(2)] = np.sum(mat1, axis=1)
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for the thorough explanation. it's a shame about not being able to use the out parameter. It would really save me a lot of headache!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.