Problem: Write a program in python to add two matrices.
Example:
m1 = [[1,2], [8,1]] m2 = [[1,1], [1,1]] m1+m2 = [[2,3], [9,2]]
In python, we can easily represent a matrix using a nested list.
For example, m1 = [[1,2],[8,1]]
is a list in which each element itself is a list.
Each row in a matrix can be denoted by m1[i] and the element in the ith row and jth column as m1[i][j]
.
So using a nested for loop we can easily add elements of the first matrix to their corresponding element of the second matrix.
Method 1: Matrix Addition Using Nested For Loop
#Matrix I
m1 = [[1,2],
[8,1]]
#Matrix II
m2 = [[1,1],
[1,1]]
#Initialize resultant matrix with 0
res = [[0,0],
[0,0]]
for i in range(len(m1)):
for j in range(len(m1[0])):
res[i][j] = m1[i][j] + m2[i][j]
print(res)
Output:
[[2, 3], [9, 2]]
In the above program, we have used len(m1)
to find the number of rows and len(m1[0])
to find the number of columns in the matrix m1.
Method 2: Matrix Addition using List Comprehension
In this method instead of using a nested for loop, we will use list comprehension to add matrices.
I highly recommend you to read our list comprehension tutorial if you don’t know what it is?
#Matrix I
m1 = [[1,2],
[8,1]]
#Matrix II
m2 = [[1,1],
[1,1]]
res = [[m1[i][j] + m2[i][j] for j in range(len(m1[0]))] for i in range(len(m1))]
print(res)
Output:
[[2, 3, 2], [9, 2, 3]]