Replace the diagonal elements of a matrix with sum of other elements in the row in Python
Here's a vectorized approach on a NumPy array a
as input -
In [171]: a # Input arrayOut[171]: array([[ 0, 1, 2, 3, 4], [ 5, 6, 7, 8, 9], [10, 11, 12, 13, 14], [15, 16, 17, 18, 19], [20, 21, 22, 23, 24]])# Get row and column indices of diag elements In [172]: row,col = np.diag_indices_from(a)# Assign the sum of each row except the diag elems into diag positionsIn [173]: a[row,col] = a.sum(axis=1) - a[row,col]# Updated arrayIn [174]: aOut[174]: array([[10, 1, 2, 3, 4], [ 5, 29, 7, 8, 9], [10, 11, 48, 13, 14], [15, 16, 17, 67, 19], [20, 21, 22, 23, 86]])
Let's manually compute the summations and cross-check against the diagonal elements -
In [175]: a[0,1] + a[0,2] + a[0,3] + a[0,4]Out[175]: 10In [176]: a[1,0] + a[1,2] + a[1,3] + a[1,4]Out[176]: 29In [177]: a[2,0] + a[2,1] + a[2,3] + a[2,4]Out[177]: 48In [178]: a[3,0] + a[3,1] + a[3,2] + a[3,4]Out[178]: 67In [179]: a[4,0] + a[4,1] + a[4,2] + a[4,3]Out[179]: 86