从matlab到python的尺寸误差



我想把gram-schmidt_process、matlab的算法改为python但是我有一个类似的错误

def qr_mgs(A):
m, n = A.shape
Q = A
R = np.zeros((n, n))
for i in range(n - 1):
R[i, i] = np.linalg.norm(Q[:, i])
Q[:, i] = Q[:, i] / R[i, i]
R[i, i+1:n] = np.matmul(np.transpose(Q[:, i]), Q[:, i+1:n])
Q[:, i+1:n] = Q[:, i+1:n] - np.matmul(Q[:, i], R[i, i+1:n])
R[n, n] = np.linalg.norm(Q[:, n])
Q[:, n] = Q[:, n]/R[n, n]
return Q, R
ValueError: matmul: Input operand 1 has a mismatch in its core dimension 0, with gufunc signature (n?,k),(k,m?)->(n?,m?) (size 2 is different from 3)

怎么了???

是关于尺寸问题吗?

试着用一些简单的例子调试代码。

qr_mgs(np.arange(1, 10).reshape(3,3))

当我调试你的代码时,这一行的尺寸不匹配:

Q[:, i+1:n] = Q[:, i+1:n] - np.matmul(Q[:, i], R[i, i+1:n])

Q[:, i]具有长度3,R[:, i+1:n]具有长度2。

你可能有一些索引问题,我不是代数专家,所以不能帮助你修复算法。

最新更新