Python Program to Add Two Matrices
Matrix Addition operation is adding two matrices by adding the corresponding elements in both the matrices to get a resultant matrix containing same number of rows and columns of the considered matrices.
We can do this:
- Using Nested Loops
- Using Nested List Comprehension
Using Nested Loops :
IMPLEMENTATION :
S = [[-5, 2, -2],
[2, -3, 4],
[-1, 3, -3]]
C = [[3, 2, 8],
[6, 1, 2],
[5, 5, 1]]
result = [[-1, 2, 3],
[4, -1, 3],
[2, 4, -1]]
for i in range(len(S)):
for j in range(len(S[0])):
result[i][j] = S[i][j] + C[i][j]
for r in result:
print(r)OUTPUT :
[-2, 4, 6] [8, -2, 6] [4, 8, -2]
Using Nested List Comprehension :
IMPLEMENTATION :
L = [[2, 2, 1],
[1, 5, 0],
[0, 0, 1]]
A = [[5, 7, 1],
[0, 3, 0],
[1, 0, 8]]
result = [[L[i][j] + A[i][j] for j in range (len(L[0]))] for i in range(len(L))]
for r in result:
print(r)OUTPUT :
[7, 9, 2] [1, 8, 0] [1, 0, 9]
Time Complexity : O(N * 2)
Auxiliary Complexity : O(N * N)
Leave a Reply