How to Sum Up Diagonal Elements of an Matrix in Python


In this example we will show how to get the sum of the main diagonal elements of a 3*3 matrix with Python.

Source Code

#! /usr/bin/env python3
# -*- coding: utf-8 -*-

print('Please input 9 values to create a 3x3 matrix')
a = []
sum = 0.0
for i in range(3):
    a.append([])
    for j in range(3):
        a[i].append(float(input("input num: ")))
for i in range(3):
    sum += a[i][i]
print('The matrix is successfully created!n')
print('The sum of matrix diagonal elements: %s'%sum)

Output:

Please input 9 values to create a 3x3 matrix
input num: 123
input num: 456
input num: 789
input num: 345
input num: 345
input num: 367
input num: 896
input num: 134
input num: 567
The matrix is successfully created!

The sum of matrix diagonal elements: 1035.0
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments