Algorithm


1. Initialize two matrices, A and B, with the same dimensions.
2. Create a new matrix, C, with the same dimensions as A and B to store the result.
3. Iterate through each row and column of matrices A and B:
    a. Read the element at the current position from matrix A (A[i][j]).
    b. Read the element at the current position from matrix B (B[i][j]).
    c. Add the corresponding elements from matrices A and B and store the result in matrix C at the same position (C[i][j] = A[i][j] + B[i][j]).
4. Display or return the matrix C, which contains the sum of matrices A and B.

Code Examples

#1 Code Example- Matrix Addition using Nested Loop

Code - Python Programming

# Program to add two matrices using nested loop

X = [[12,7,3],
    [4 ,5,6],
    [7 ,8,9]]

Y = [[5,8,1],
    [6,7,3],
    [4,5,9]]

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]

for r in result:
   print(r)
Copy The Code & Try With Live Editor

Output

x
+
cmd
[17, 15, 4]
[10, 12, 9]
[11, 13, 18]

#2 Code Example- Matrix Addition using Nested List Comprehension

Code - Python Programming

# Program to add two matrices using list comprehension

X = [[12,7,3],
    [4 ,5,6],
    [7 ,8,9]]

Y = [[5,8,1],
    [6,7,3],
    [4,5,9]]

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

for r in result:
   print(r)
Copy The Code & Try With Live Editor
Advertisements

Demonstration


Python Programing Example to Add Two Matrices-DevsEnv