# Program to find diagonal sum of a matrix in Python

PythonServer Side ProgrammingProgramming

Suppose we have a square matrix; we have to find the sum of the matrix diagonals. So only include the sum of all of the elements on the primary diagonal and all the elements on the secondary diagonal and ignore the crossing element.

So, if the input is like

 10 5 9 6 8 15 3 2 3 8 12 3 2 11 7 3

then the output will be The primary diagonal elements are [10,15,12,3] sum is 40, secondary diagonal [6,3,8,2] sum is 19, so total sum 59.

To solve this, we will follow these steps −

• m := row count of matrix

• if m is same as 1, then

• return matrix[0, 0]

• count := 0

• for i in range 0 to m - 1, do

• count := count + matrix[i, i]

• count := count + matrix[i, (-1 - i)]

• if m is odd, then

• ind := quotient of m/2

• count := count - matrix[ind, ind]

• return count

## Example (Python)

Let us see the following implementation to get better understanding −

Live Demo

def solve(matrix):
m = len(matrix)
if m == 1: return matrix

count = 0
for i in range(m):
count += matrix[i][i]
count += matrix[i][-1 - i]

if m % 2 == 1: count -= matrix[m // 2][m // 2]

return count

matrix = [[10,5,9,6],[8,15,3,2],[3,8,12,3],[2,11,7,3],]
print(solve(matrix))

## Input

[[10,5,9,6],[8,15,3,2],[3,8,12,3],[2,11,7,3]]

## Output

59