Search code examples
pythonarraysnumpydiagonal

fill off diagonal of numpy array fails


I'm trying to the fill the offset diagonals of a matrix:

loss_matrix = np.zeros((125,125))

np.diagonal(loss_matrix, 3).fill(4)

ValueError: assignment destination is read-only

Two questions:

1) Without iterating over indexes, how can I set the offset diagonals of a numpy array?

2) Why is the result of np.diagonal read only? The documentation for numpy.diagonal reads: "In NumPy 1.10, it will return a read/write view and writing to the returned array will alter your original array."

np.__version__

'1.10.1'

Solution

  • Judging by the discussion on the NumPy issue tracker, it looks like the feature is stuck in limbo and they never got around to fixing the documentation to say it was delayed.

    If you need writability, you can force it. This will only work on NumPy 1.9 and up, since np.diagonal makes a copy on lower versions:

    diag = np.diagonal(loss_matrix, 3)
    
    # It's not writable. MAKE it writable.
    diag.setflags(write=True)
    
    diag.fill(4)