我想在矩阵的数组中迭代地相乘
matrix[0] = [[1,2,3,4], [1,2,3,4], [1,2,3,4], [1,2,3,4]]
matrix[1] = [[1,2,3,4], [1,2,3,4], [1,2,3,4], [1,2,3,4]]
matrix[3] = [[1,2,3,4], [1,2,3,4], [1,2,3,4], [1,2,3,4]]
matrix[4] = [[1,2,3,4], [1,2,3,4], [1,2,3,4], [1,2,3,4]]
matrix[5] = [[1,2,3,4], [1,2,3,4], [1,2,3,4], [1,2,3,4]]
matrix[6] = [[1,2,3,4], [1,2,3,4], [1,2,3,4], [1,2,3,4]]
乘法矩阵[0]和矩阵[1]的结果将乘以下一个矩阵矩阵[3]。这个结果将再次与下一个结果相乘。这个过程应该按顺序进行。 任何想法或解决方案?感谢
答案 0 :(得分:0)
您所描述的是reduce
操作:
Python 2.7: built-in functions: reduce
假设您已定义此矩阵乘法函数:
def multiply(a, b):
num_r, num_c, num_i = len(a), len(b[0]), len(a[0])
m = [num_c * [None] for r in range(num_r)]
for r in range(num_r):
for c in range(num_c):
x = 0
for i in range(num_i):
x += a[r][i] * b[i][c]
m[r][c] = x
return m
你有这个矩阵列表:
matrices = [[[1,2,3,4], [1,2,3,4], [1,2,3,4], [1,2,3,4]],
[[1,2,3,4], [1,2,3,4], [1,2,3,4], [1,2,3,4]],
[[1,2,3,4], [1,2,3,4], [1,2,3,4], [1,2,3,4]],
[[1,2,3,4], [1,2,3,4], [1,2,3,4], [1,2,3,4]],
[[1,2,3,4], [1,2,3,4], [1,2,3,4], [1,2,3,4]],
[[1,2,3,4], [1,2,3,4], [1,2,3,4], [1,2,3,4]]]
现在,您可以将一个矩阵按顺序乘以reduce
:
print reduce(multiply, matrices)
答案 1 :(得分:0)
我明白了(操作*是矩阵乘法过程的简化):
for i in range(6):
A = matrix[i]
B = matrix[i+1]
C = A * B
matrix [i+1] = C
return C
让我知道是否有其他更好的方法来做到这一点。感谢