假设A是一个MxN矩阵。我想用它的转置乘以A。是否有可能使用纯嵌套循环(即不使用np.transpose)?当我尝试遍历它时,我不知道如何解决范围问题,因为结果的形状与A不同。
假设A是3x4。那么A*(A^T)的结果将是3x3。result[i][j]
中的i
和j
都不能大于4。那么如何按行和按列迭代?
发布于 2020-01-14 14:08:52
试试这个。没有numpy,常规列表,可以转移到任何语言
for i in range(len(A)):
for j in range(len(A)):
# R must be initialized above with the proper shape (n x n)!
R[i][j] = 0
for k in range(len(A[0])):
R[i][j] += A[i][k] * A[j][k]
发布于 2020-01-14 14:07:36
是的,这是可能的,如果你想完全依靠嵌套,你可以尝试一下。
x = [[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11]]
result = []
for k in range(len(x)):
temp = []
for i in range(len(x)):
tempSum = 0
for j in range(len(x[0])):
tempSum += x[k][j]*x[i][j]
temp.append(tempSum)
result.append(temp)
print(result)
输出:
[[14, 38, 62], [38, 126, 214], [62, 214, 366]]
您可以使用numpy进行验证:
>>> x = np.arange(12).reshape(3,4)
>>> x@x.T
array([[ 14, 38, 62],
[ 38, 126, 214],
[ 62, 214, 366]])
发布于 2020-01-14 14:07:59
通过直接使用矩阵乘法定义和标准数字广播,这应该是很有可能的:
import numpy as np
def matrix_multiplication_nested_loop(A, B):
res = np.zeros((A.shape[0], B.shape[1]))
for _x in range(A.shape[0]):
for _y in range(B.shape[1]):
res[_x, _y] = np.sum(A[_x, :] * B[:, _y])
return res
A = np.array([[1, 2, 3, 4], [5, 6, 7, 8], [0, 1, 2, 1]])
B = np.array([[1, 5, 0], [2, 6, 1], [3, 7, 2], [4, 8, 1]]) # A.T
https://stackoverflow.com/questions/59728130
复制相似问题