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, a matrix can be represented using nested list. For example m1 = [[1,2],[8,1]]
is a list having each element itself a list. Each row in a matrix can be denoted by m1[i]
and theelement in the ith row and jth column as m1[i][j]
.
So using a nested for loop we can easily add each element of the first matrix to the corresponding element of the second matrix.
Method 1: Matrix Addition Using Nested For Loop
Recommended:
#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 number of rows and len(m1[0])
to find the number of column in the metrix m1.
Method 2: Matrix Addition using List Comprehension
In this method instead of using 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]]
If you have any suggestions or doubts then comment below.