[Solved] Sum of Diagonal Elements in Matrix in Python Code

[Solved] Sum of Diagonal Elements in Matrix in Python Code

We can save the matrix as a list of lists in Python i.e. two dimensional list. To find the sum of diagonal elements, we are using a Python list to save the matrix elements and Python for-loop to traverse diagonal elements.

This coding question has been asked in many interviews (especially for the freshers). The difficulty level is easy.

Check the following Python code. It’s very simple and self-descriptive.

matrix = [[1, 4, 5],
  		[5, 5, 7],
  		[4, 1, 3]]

sum = 0
for i in range(len(matrix)):
  sum = sum+matrix[i][i] 

print(f"Sum of diagonal elements in matrix = {sum}")

Output:

Sum of diagonal elements in matrix = 9

Note: We can only find the sum of diagonal elements in Python when the matrix is square. A square matrix is a matrix that has the same number of rows and columns.

You can modify the above code to check whether the given matrix is square or not before finding the sum of diagonal elements.

matrix = [[1, 4, 5],
  		[5, 5, 7],
  		[4, 1, 3]]

if len(matrix) != len(matrix[0]):
  print("Matrix is not a square matrix.")
else:
  sum = 0
  for i in range(len(matrix)):
    sum = sum+matrix[i][i] 
  print(f"Sum of diagonal elements in matrix = {sum}")

Complexity:

Let’s say the size of the matrix is n*n where the number of rows and columns is the same as n.

In the above code, we are traversing each element in the rows (or columns) once, using a single for loop. So the complexity of this algorithm is O(n).

If you want to improve your coding skills, practice solving similar coding questions.

Happy Coding!

Leave a Reply

Your email address will not be published. Required fields are marked *