ValueError Traceback (most recent call last) <ipython-input-20-000300cc57e6> in <module> ----> 1 QR(M) <ipython-input-19-490e012c78fb> in QR(A) 6 a = R[j:, j] 7 v = np.zeros(m) ----> 8 v[j:] = a + np.sign(a[0]) * np.linalg.norm(a) * np.eye(1, m, j) 9 v = v / np.linalg.norm(v) 10 H = np.eye(m) - 2 * np.outer(v, v) ValueError: operands could not be broadcast together with shapes (9,) (1,10) 会报这个错
时间: 2024-03-03 17:51:15 浏览: 286
这个错误是因为 `np.eye(1, m, j)` 返回的是一个形状为 `(1, m)` 的矩阵,而 `a` 是一个形状为 `(9,)` 的向量,无法直接相加。可以将 `np.eye(1, m, j)` 改为 `np.eye(m)[j:]`,如下所示:
```
def QR(A):
m, n = A.shape
Q = np.eye(m)
R = A.copy()
for j in range(min(m, n)):
a = R[j:, j]
v = np.zeros(m)
v[j:] = a + np.sign(a[0]) * np.linalg.norm(a) * np.eye(m)[j:]
v = v / np.linalg.norm(v)
H = np.eye(m) - 2 * np.outer(v, v)
Q = Q @ H
R = H @ R
coeff_matrix = sp.Matrix(np.zeros((10, 10)))
for i in range(10):
for j in range(10):
coeff_matrix[i, j] = sp.Matrix(x[i]).coeff(sp.Symbol('a{}'.format(j + 1)))
return(coeff_matrix)
```
这里使用 `np.eye(m)[j:]` 来获取第 `j` 行及其之后的单位矩阵。
阅读全文