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 = []
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


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

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

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.

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 = []
    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

Need Your Help

A Scala/Java media framework?

java swing scala media

I had the idea to start investigating in creating and using media components in Java but I didn't find any convincing framework. The two that I found were

Running Qt application built for Linux, on windows

linux windows qt qt4 qmake

I have a Qt application which I built on Linux. I would like to run the same application on Windows. Is it possible? If yes, how? The Qt application software that I downloaded and used, is version ...