Reputation: 51
def addM(a, b):
res = []
for i in range(len(a)):
row = []
for j in range(len(a[0])):
row.append(a[i][j]+b[i][j])
res.append(row)
return res
I found this code here which was made by @Petar Ivanov, this code adds two matrices, i really don't understand the 3rd line, why does he use len(a) and the 5th line, why does he use len(a[0]). In the 6th line, also why is it a[i][j] +b[i][j]?
Upvotes: 0
Views: 6076
Reputation: 17871
The matrix here is a list of lists, for example a 2x2 matrix will look like: a=[[0,0],[0,0]]
. Then it is easy to see:
len(a)
- number of rows.len(a[0])
- number of columns (since this is a matrix, the length of a[0]
is the same as length of any a[i]
).i
is the number of row, j
is the number of column and a[i][j]+b[i][j]
is simply adding up the elements of two matrices which are placed in the same locations in the matrices. For all this to work, a
and b
should be of the same shapes (so, numbers of rows and columns would match).
Upvotes: 2