Sum of diagonal elements in a matrix
Use numpy library which is powerful for any matrix calculations. For your specific case:
import numpy as np
a = [[11,2,4],[4,5,6],[10,8,-12]]
b = np.asarray(a)
print('Diagonal (sum): ', np.trace(b))
print('Diagonal (elements): ', np.diagonal(b))
You can easily install numpy with pip or other ways that you will find on many webs.
If you want all the diagonals, and not just the main diagonal, check this that also uses numpy.
EDIT
mhawke, if you want to calculate antidiagonal (secondary diagonal), as explained in wikipedia, you can flip the matrix in numpy
import numpy as np
a = [[11,2,4],[4,5,6],[10,8,-12]]
b = np.asarray(a)
b = np.fliplr(b)
print('Antidiagonal (sum): ', np.trace(b))
print('Antidiagonal (elements): ', np.diagonal(b))
getting total and diagonal sum from a squared matrix
squared_matrix = [[2,3,4],[4,3,3],[3,3,4]]
s, ds = get_sum(squared_matrix)
def get_sum(diag_mat):
n = len(diag_mat)
total = sum([diag_mat[i][j] for i in range(n) for j in range(j)]
d_sum = sum([diag_mat[i][j] if i==j else 0 for i in range(n) for j in range(j)]
return d_sum, total
Try this for summing your second diagonal:
sum(a[i][n-i-1] for i in range(n))
The inner loop accesses these entries:
>>> n = 3
>>> [(i, n-i-1) for i in range(n)]
[(0, 2), (1, 1), (2, 0)]
And the summed value of this diagonal for your sample matrix is:
>>> n = 3
>>> sum(a[i][n-i-1] for i in range(n))
19
The mistake in your code is to use the same expression for both dimensions:
a[n-i-1][n-i-1]
which will process the first diagonal again in reverse order [(2, 2), (1, 1), (0, 0)]
giving you the same sum twice.