在矩阵乘法 python 语言中删除和插入值
deleting and inserting values in matrix multiplication python language
我想在一个矩阵的数组中迭代相乘
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]]
matrix[0]和matrix[1]相乘的结果将乘以矩阵的下一个数组matrix[3]。这个结果将再次与下一个相乘。该过程应按顺序进行。
任何想法或解决方案?谢谢
您描述的是 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)
我明白了(操作*是矩阵乘法过程的简化):
for i in range(6):
A = matrix[i]
B = matrix[i+1]
C = A * B
matrix [i+1] = C
return C
如果有其他更好的方法,请告诉我。谢谢
我想在一个矩阵的数组中迭代相乘
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]]
matrix[0]和matrix[1]相乘的结果将乘以矩阵的下一个数组matrix[3]。这个结果将再次与下一个相乘。该过程应按顺序进行。 任何想法或解决方案?谢谢
您描述的是 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)
我明白了(操作*是矩阵乘法过程的简化):
for i in range(6):
A = matrix[i]
B = matrix[i+1]
C = A * B
matrix [i+1] = C
return C
如果有其他更好的方法,请告诉我。谢谢