- Related Questions & Answers
- How to find the sum of anti-diagonal elements in a matrix in R?
- Program to print a matrix in Diagonal Pattern.
- Program to convert given Matrix to a Diagonal Matrix in C++
- Program to find sum each of the diagonal path elements in a binary tree in Python
- Diagonal product of a matrix - JavaScript
- Program to check diagonal matrix and scalar matrix in C++
- Python Program to find the transpose of a matrix
- Find the transpose of a matrix in Python Program
- How to find the sum of diagonal elements in a table in R?
- Program to find the sum of elements that forms a Z shape on matrix in Python
- Program to sort each diagonal elements in ascending order of a matrix in C++
- Filling diagonal to make the sum of every row, column and diagonal equal of 3×3 matrix using c++
- Python program to find Cumulative sum of a list
- Print matrix in diagonal pattern
- Diagonal Sum of a Binary Tree in C++?

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

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

Let us see the following implementation to get better understanding −

def solve(matrix): m = len(matrix) if m == 1: return matrix[0][0] 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))

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

59

Advertisements