Daidalos August 06, 2019

Example of how to add a number to a matrix diagonal elements in python ?

### Replace the diagonal element by a same number

To replace the diagonal element by a same number, a solution is to use the numpy function numpy.fill_diagonal

>>> import numpy as np
>>> A = np.arange(9).reshape(3,3)
>>> A
array([[0, 1, 2],
       [3, 4, 5],
       [6, 7, 8]])
>>> np.fill_diagonal(A, 100)
>>> A
array([[100,   1,   2],
       [  3, 100,   5],
       [  6,   7, 100]])


### Add a number to the diagonal elements of a matrix

It is also possible to add a number to the diagonal elements of a matrix using the numpy function numpy.diagonal pour ajouter un nombre aux éléments de la diagonale

>>> A = np.arange(9).reshape(3,3)
>>> A
array([[0, 1, 2],
       [3, 4, 5],
       [6, 7, 8]])
>>> np.fill_diagonal(A, A.diagonal() + 100)
>>> A
array([[100,   1,   2],
       [  3, 104,   5],
       [  6,   7, 108]])


### References

numpy.fill_diagonal docs.scipy
How to add only to diagonals of array in Python? stackoverflow
numpy.diagonal docs.scipy
numpy.triu_indices docs.scipy