;

Python Program to Add Two Matrices


Tutorialsrack 23/04/2020 Python

In this Python program, we will learn how to add two matrices. 

Here is the code of the program to add two matrices.

Program 1: Program to add two matrices using nested For loop

Program to add two matrices using nested For loop
# Program to add two matrices using nested For loop

# 3x3 Matrix 1
X = [[6,7,3],
    [4 ,11,6],
    [7 ,8,9]]

# 3x3 Matrix 2
Y = [[8,8,1],
    [6,6,3],
    [4,5,9]]

# Output Matrix 
result = [[0,0,0],
         [0,0,0],
         [0,0,0]]

# iterate through rows
for i in range(len(X)):
   # iterate through columns
   for j in range(len(X[0])):
       result[i][j] = X[i][j] + Y[i][j]

print("\nOutput of Addition of Two Matrices:")
for r in result:
   print(r) 
Output

Output of Addition of Two Matrices:

[14, 15, 4]

[10, 17, 9]

[11, 13, 18]

Program 2: Program to add two matrices using list comprehension

Program to add two matrices using list comprehension
# Program to add two matrices using nested list comprehension
# 3x3 Matrix 1
X = [[6,7,3],
    [4 ,11,6],
    [7 ,8,9]]

# 3x3 Matrix 2
Y = [[8,8,1],
    [6,6,3],
    [4,5,9]]

result = [[X[i][j] + Y[i][j]  for j in range(len(X[0]))] for i in range(len(X))]

print("\nOutput of Addition of Two Matrices:")
for r in result:
   print(r)
Output

Output of Addition of Two Matrices:

[14, 15, 4]

[10, 17, 9]

[11, 13, 18]


Related Posts



Comments

Recent Posts
Tags