Functions - Matrix - Sum of diagonal elements

# Functions and Matrix
# Matrix Sum of diagonal elements

# Function - Read Matrix
def fn_read(r, c):
    M = []
    print("Enter values of Matrix : ")
    for i in range(0,r,1):
        tmp = []
        for j in range(0,c,1):
            ele = int(input())
            tmp.append(ele)
        M.append(tmp)
    return M

# Function - Display Matrix
def fn_display(M):
    for row in M:
        for ele in row:
            print(ele, end=" ")
        print()

# Function - Sum of diagonal elements
def fn_add(MA, r):
    s = 0
    for i in range(0,r,1):
        s += MA[i][i]
    return s

# Main Program

import sys

Mat_A = []

print("Enter number of rows and columns :")
r1 = int(input("Matrix 1 - Row : "))
c1 = int(input("Matrix 1 - Column : "))

# Addition and Subtraction
if (r1 != c1):
    print("Not a square matrix.")
    print("Cannot Add the diagonal elements.")
else:
    Mat_A = fn_read(r1, c1)
       
    print("Given Matrix : ")   
    fn_display(Mat_A)
   
    dsum = fn_add(Mat_A, r1)
    print("Sum of diagonal elements of given matrices :", dsum)   
   

No comments:

Post a Comment

Don't be a silent reader...
Leave your comments...

Anu