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))
try this:
Try this for summing your second diagonal:
The inner loop accesses these entries:
And the summed value of this diagonal for your sample matrix is:
The mistake in your code is to use the same expression for both dimensions:
which will process the first diagonal again in reverse order
[(2, 2), (1, 1), (0, 0)]
giving you the same sum twice.