0

How can I add matrices (list of lists) in python? I know that I can do this:

X = [[12,7,3],
    [4 ,5,6],
    [7 ,8,9]]

Y = [[5,8,1],
    [6,7,3],
    [4,5,9]]

result = [[0,0,0],
         [0,0,0],
         [0,0,0]]

# iterate through rows
for i in range(len(X)):
   # iterate through columns
   for j in range(len(X[0])):
       result[i][j] = X[i][j] + Y[i][j]

for r in result:
   print(r)

But what if the the input of the two lists have different numbers of rows or columns? I need to check first to see if the number of rows and columns are the same before adding and I'm not sure how to do this.

8
  • 2
    Is there a reason you can't use numpy for this? Commented Feb 4, 2016 at 21:34
  • if A is an n × m matrix and B is an m × p matrix, their matrix product AB is an n × p matrix. en.wikipedia.org/wiki/Matrix_multiplication Commented Feb 4, 2016 at 21:36
  • Using numpy the matrix multiplication can be done even using the common multiplication operators, there is absolutely no need for all this mess... Commented Feb 4, 2016 at 21:38
  • 2
    I'm not trying to multiply the matrices though. I need to ADD them Commented Feb 4, 2016 at 21:39
  • 4
    If all you want to do is check that they have the same dimensions, just do (assert len(X) == len(Y)) and (len(X[0]) == len(Y[0])) (assuming that you know all sub-lists will be of the same length) Commented Feb 4, 2016 at 21:41

1 Answer 1

1

Do the size check and then build the result directly with a doubly-nested list comprehension. Numpy is better, but if you want to avoid an import, this will do.

X = [[12,7,3],
     [4 ,5,6],
     [7 ,8,9]]

Y = [[5,8,1],
     [6,7,3],
     [4,5,9]]

if len(X) == len(Y) and len(X[0]) == len(Y[0]):
    result = [[X[i][j] + Y[i][j] for j in range(len(X[0]))]
              for i in range(len(X))]

print result

Output:

[[17, 15, 4], [10, 12, 9], [11, 13, 18]]
Sign up to request clarification or add additional context in comments.

2 Comments

the above code will throw an error if the dims don't match, right?
Only because result isn't defined. To throw a proper exception, add an else clause of your choice.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.