I am trying to find out the sum of the diagonal elements in a matrix. Here, n is the size of the square matrix and a is the matrix. Can someone explain this to me what is happening here.
n = 3
a = [[11,2,4],[4,5,6],[10,8,-12]]
sum_first_diagonal = sum(a[i][i] for i in range(n))
sum_second_diagonal = sum(a[n-i-1][n-i-1] for i in range(n))
print(str(sum_first_diagonal)+" "+str(sum_first_diagonal))
I don't understand why no one posted any good solution. Here is as descent solution:
Here arr is a 2d list.
I found a simple algorithm to accomplish this task.
Pass in your list. This should work for you :)
Since you know the positions of the diagonal elements for row
i
, you can write it quite densely like:And, for odd sized matrices, you shouldn't add the center element twice:
Use numpy library which is powerful for any matrix calculations. For your specific case:
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
getting total and diagonal sum from a squared matrix