Matrix Addition In Python - List
I'm trying to write Matrix Addition function using Python. Here is the code I've been trying, but it gives me a list index error and I cannot figure out why. def matrixADD(A,B): Z
Solution 1:
>>> A = [[2,4], [7,0], [6,3]]
>>> B = [[3,1], [-1,8], [-3, 3]]
>>> Z = [map(sum, zip(*t)) for t in zip(A, B)]
>>> Z
[[5, 5], [6, 8], [3, 6]]
As for how you could fix your current code:
Z = []
for i in range(len(A)):
row = []
for j in range(len(A[i])):
row.append(A[i][j] + B[i][j])
Z.append(row)
The important parts here being that you cannot just assign to Z[i][j]
unless that row/column already exists, so you need to construct each inner list separately and append them to Z
. Also the inner loop needs to end at the length of a row, so I changed range(len(A))
to range(len(A[i]))
.
Solution 2:
len(A) = 3
but you matrix have dimension 3x2 so when you try to access A[2][2] (because column is between 0 and len(A)) you are out of bounds.
Solution 3:
For column
you are using range 0 to len(A) (which is 3). A[i][2] will be out of range, because A[i]'s length is only 2.
Try using column range to end a len(A[i]) instead of len(A):
defmatrixADD(A,B):
Z = []
#TODOfor i inrange(0,len(A)):
for column inrange(0, len(A[i])):
result = A[i][column] + B[i][column]
Z[i][j] = (result)
return Z
Post a Comment for "Matrix Addition In Python - List"