def mat_simp(M): n, p = M.shape for i in range(n): for j in range(p): M[i, j] = M[i, j].simplify().expand().simplify() return M def mat(u): n = len(u) M = sp.zeros(n, n) for j in range(n): cj = sp.Matrix([int(i == j) for i in range(n)]) Mcj = cj-2*cj.dot(u)/u.norm()**2*u for i in range(n): M[i, j] = Mcj[i] return M def DecompositionQR(A): n, p = A.shape if n != p or A.det() == 0: raise Exception("Les données ne sont pas correctes") AA = A.copy() O = sp.eye(n) for i in range(n): if not AA[i+1:, i].is_zero_matrix: B = AA.copy() for j in range(i): B[j, i] = 0 Ci = sp.Matrix([int(k == i) for k in range(n)]) S = mat_simp(mat(Ci-B[:, i]/B[:, i].norm())) O = S@O AA = S@AA return O.transpose(), AA修改这段代码,使她可以做QR分解
时间: 2024-02-28 08:55:31 浏览: 49
以下是修改后的代码,可以进行 QR 分解:
```
def mat_simp(M):
n, p = M.shape
for i in range(n):
for j in range(p):
M[i, j] = M[i, j].simplify().expand().simplify()
return M
def mat(u):
n = len(u)
M = sp.zeros(n, n)
for j in range(n):
cj = sp.Matrix([int(i == j) for i in range(n)])
Mcj = cj-2*cj.dot(u)/u.norm()**2*u
for i in range(n):
M[i, j] = Mcj[i]
return M
def qr_decomposition(A):
n, p = A.shape
if n != p or A.det() == 0:
raise Exception("Les données ne sont pas correctes")
AA = A.copy()
Q = sp.eye(n)
for i in range(n):
if not AA[i+1:, i].is_zero_matrix:
B = AA.copy()
for j in range(i):
B[j, i] = 0
Ci = sp.Matrix([int(k == i) for k in range(n)])
S = mat_simp(mat(Ci-B[:, i]/B[:, i].norm()))
Q = Q@S
AA = S@AA
R = AA
return Q.transpose(), R
```
将函数名 `DecompositionQR` 改成了 `qr_decomposition`,并且修改了函数主体部分,使其能够进行 QR 分解。
阅读全文