Python program to add two matrices

Addition of two matrices in python

Problem description :

The program gets two matrices as input from the user and returns the sum of two matrices.

For adding two matrices the input matrices should be of same order.

Example,

        1 2 3

A=   4 5 6         Order of A => 3x3

        7 8 9


        1 1 1

B=   2 2 2          Order of B => 3x3

        3 3 3


            2   3   4

A+B=  6   7   8

            10 11 12


Whereas fo the matrices,

         1 2 3

A=    4 5 6            Order of A => 3x3

         7 8 9


        1 2

B=   3 5                Order of B => 3x2

        6 7


Here the addition of two matrices is not possible as the order of the input matrices A and B are not same.

PrerequisiteGetting matrix input from user

Procedure :

1. Start.

2. Get two matrices from user, say m1 and m2.

3. Create an empty list, result matrix.

4. loop (0 to row length)

    => create an empty list, l.

    => loop (0 to column length)

         => add m1[i][j] and m3[i][j]

         => append the sum to list, l .

    => append the list to the result matrix

5. Print the result matrix.

6. End.

Code :

#function to print the matrix

def printMatrix(matrix):

for i in range(len(matrix)):

for j in range(len(matrix[i])):

print(matrix[i][j], end=" ")

print()

#function to get matrix input from user

def GetMatrix(matrix) :

r = int(input("Enter the number of rows : "))

c = int(input("Enter the number of columns : "))

for row in range(r):

l = list(map(int,input("Enter elements of row separated by space : ").split(" ")))

matrix+=[l]

#initializing the input matrices

m1=[]

m2=[]

print("Matrix 1 : ")

#Getting the matrix from user

GetMatrix(m1)

print("Matrix 2 : ")

GetMatrix(m2)

#initializing sum matrix

sumMatrix = []

for row in range(len(m1)):

added_row = []

for col in range(len(m1[row])):

                #adding the corresponding elements of two matrices

sum = m1[row][col] + m2[row][col]

                #appending the sum value to a list

added_row+=[sum]

        #appending the list to the sum matrix

sumMatrix += [added_row]

#print the sum matrix

print("Sum of two matrices : ")

printMatrix(sumMatrix)

Output :

Matrix addition in python
Matrix addition - Output






Comments

Popular posts from this blog

Finding the percentage in python - HackerRank solution

HackerRank challenges with solutions (Rearrangement, Formula, Word sorting, Numbers, Sentence)

ginortS in Python - HackerRank solution