I’m trying to write a function that adds two matrices to pass the following doctests:
>>> a = [[1, 2], [3, 4]]
>>> b = [[2, 2], [2, 2]]
>>> add_matrices(a, b)
[[3, 4], [5, 6]]
>>> c = [[8, 2], [3, 4], [5, 7]]
>>> d = [[3, 2], [9, 2], [10, 12]]
>>> add_matrices(c, d)
[[11, 4], [12, 6], [15, 19]]
So I wrote a function:
def add(x, y):
return x + y
And then I wrote the following function:
def add_matrices(c, d):
for i in range(len(c)):
print map(add, c[i], d[i])
And I sort of get the right answer.
Matrix library
You can use the
numpymodule, which has support for this.Home-grown solution: heavyweight
Assuming you wanted to implement it yourself, you’d set up the following machinery, which would let you define arbitrary pairwise operations:
Now adding pairwise methods is as easy as pie:
Example:
You can even add pairwise exponentiation, negation, binary operations, etc. I do not demonstrate it here, because it’s probably best to leave * and ** for matrix multiplication and matrix exponentiation.
Home-grown solution: lightweight
If you just want a really simple way to map an operation over only two nested-list matrices, you can do this:
Demo:
With an additional if-else and keyword argument, you can use indices in your lambda. Below is an example of how to write a matrix row-order
enumeratefunction. The if-else and keyword were omitted above for clarity.edit
So we could write the above
add_matricesfunction like so:Demo: