0

I'm trying to change elements of the diagonal(1) of a matrix but I can't do it because of the error "assignment destination is read-only.

x=np.loadtxt('matrice.txt')
print(x.diagonal(1)) #2
x.diagonal(1)[0]=3
ValueError: assignment destination is read-only

1 Answers1

0

In numpy docs for diagonal it is said

Starting in NumPy 1.9 it returns a read-only view on the original array. Attempting to write to the resulting array will produce an error.

In some future release, it will return a read/write view and writing to the returned array will alter your original array. The returned array will have the same type as the input array.

If you don’t write to the array returned by this function, then you can just ignore all of the above.

If you depend on the current behavior, then we suggest copying the returned array explicitly, i.e., use np.diagonal(a).copy() instead of just np.diagonal(a). This will work with both past and future versions of NumPy.

So you should use np.diagonal(a).copy() to get modifiable array.

If you need to edit a diagonal of your matrix you can use this answer by Hans Then.

def kth_diag_indices(a, k):
    rows, cols = np.diag_indices_from(a)
    if k < 0:
        return rows[-k:], cols[:k]
    elif k > 0:
        return rows[:-k], cols[k:]
    else:
        return rows, cols

x[kth_diag_indices(x,1)] = 2 # to make them all equal to 2
Mur4al
  • 111
  • 8
  • Thank u Mur4al. I have another problem now. I want my diagonal(1) (it has 3 elements) be only with number 2 , so i did x.diagonal(1).copy()=[2,2,2] File "", line 1 x.diagonal(1).copy()=[2,2,2] ^ SyntaxError: can't assign to function call – Renato Sciarretta Mar 27 '19 at 15:49
  • Edited the answer – Mur4al Mar 27 '19 at 16:12