If I had two matrices matrix_a = [[a, b], [c, d]], and matrix_b = [[w, x], [y, z]] and I wished to find the following matrix matrix_c = [[aw + cy, ax + cz], [bw + dy, bx + dz]] how could I do this, not only for this case but for arbitrary sizes of matrix_a and matrix_b:
a) most simply using only list comphrehensions
b) most simply using a function which took the two matrices matrix_a and matrix_b as input, and returned matrix_c
c) and/or an otherwise pythonic manner?
The following code is my current solution.
matrix_a = [[1, 1], [2, 1]]
matrix_b = [[25, 1.5], [30, 2.7]]
# so we should obtain matrix_c = [[85, 6.9], [55, 4.2]]
transposed_matrix_a =[list(i) for i in zip(*matrix_a)]
matrix_c = []
for i in range(len(matrix_a[0])):
def matrix_element(function, number):
return [function(number)*matrix_b[number][i] for i in range(len(
matrix_b[0]))]
def t_matrix_a_element(x):
return transposed_matrix_a[i][x]
c_vector = [matrix_element(t_matrix_a_element, i) for i in range(len(
transposed_matrix_a[0]))]
matrix_c.append([sum(i) for i in zip(*c_vector)])
print(matrix_c)
EDIT:
To be explicit the desired computation would be:
matrix_c = [[aw + cy, ax + cz], [bw + dy, bx + dz]]
matrix_c = [[1 x 25 + 2 x 30, 1 x 1.5 + 2 x 2.7], [1 x 25 + 1 x 30, 1 x 1.5 + 1 x 2.7]]
matrix_c = [[85, 6.9], [55, 4.2]]
and not the product:
[[aw + by, ax + bz], [cw + dy, cx + dz]]