user3407513
user3407513

Reputation: 45

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 = []
#TODO
for i in range(0,len(A)):
    for column in range(0, len(A)):
        result = A[i][column] + B[i][column]
        Z[i][column] = (result)
return Z

using the following lists:

A = [[2,4], [7,0], [6,3]]
B = [[3,1], [-1,8], [-3, 3]]

So in theory, A[0][0] + B[0][0] would equal 5, and I would want to add that value to position Z[0][0].

However I keep receiving the error: IndexError: list index out of range

Upvotes: 1

Views: 11868

Answers (3)

cwa76
cwa76

Reputation: 154

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):

def matrixADD(A,B):
    Z = []
    #TODO
    for i in range(0,len(A)):
        for column in range(0, len(A[i])):
            result = A[i][column] + B[i][column]
            Z[i][j] = (result)
    return Z

Upvotes: 0

Andrew Clark
Andrew Clark

Reputation: 208465

>>> 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])).

Upvotes: 2

Math
Math

Reputation: 2436

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.

Upvotes: 0

Related Questions