我正在尝试为可选分配做一些 QR 分解,但我没有使用 numpy:
def multiply(matrix1, matrix2):
rows_A = len(matrix1)
cols_A = len(matrix1[0])
rows_B = len(matrix2)
cols_B = len(matrix2[0])
new_matrix = [[0 for row in range(cols_B)] for col in range(rows_A)]
for i in range(len(matrix1)):
for j in range(len(matrix2[0])):
for k in range(len(matrix2)):
new_matrix[i][j] += matrix1[i][k]*matrix2[k][j]
return new_matrix
def transpose(matrix):
newmatrix = []
for i in range(len(matrix)):
newline = []
for j in range(len(matrix[i])):
newline.append(matrix[j][i])
newmatrix.append(newline)
for k in range(len(newmatrix)):
print(newmatrix[k])
return matrix
# Returns the Gramm-Schmidt orthogonalization of matrix X
def gramm_schmidt(X, inplace = False):
if not inplace:
V = [row[:] for row in X] # make a copy.
else:
V = X
k = len(X[0]) # number of columns.
n = len(X) # number of rows.
for j in range(k):
for i in range(j):
# D = < Vi, Vj>
D = sum([V[p][i]*V[p][j] for p in range(n)])
for p in range(n):
# Note that the Vi's already have length one!
# Vj = Vj - <Vi,Vj> Vi/< Vi,Vi >
V[p][j] -= (D * V[p][i])
# Normalize column V[j]
invnorm = 1.0 / sqrt(sum([(V[p][j])**2 for p in range(n)]))
for p in range(n):
V[p][j] *= invnorm
return V
def QR(matrix):
Q = gramm_schmidt(matrix)
Q_transpose = transpose(Q)
R = multiply(Q_transpose, matrix)
QR = multiply(Q, R)
print ("Q:\n")
for row in Q:
print (row)
print ("\n")
print ("R:\n")
for row in R:
print (row)
print ("\n")
print ("QR:\n")
for row in QR:
print (row)
print ("\n")
但是在我的代码中的这一行:
R = multiply(Q_transpose, matrix)
我收到此错误:
rows_A = len(matrix1)
TypeError: object of type 'NoneType' has no len()
而且我不确定为什么,因为乘法函数本身适用于我进行标准乘法时......如果有人可以提供帮助,请提前感谢!
编辑:我添加了一个返回语句来转置,是的,它实际上给出了一个转置矩阵。似乎乘数是罪魁祸首。这是它应该做的:
A:
[[12, -51, 4],
[6, 167, -68],
[-4, 24, -41]]
Q:
[[0.8571428571428571, 0.39428571428571435, -0.33142857142857135],
[0.4285714285714286, -0.9028571428571429, 0.034285714285714114],
[-0.28571428571428575, -0.17142857142857126, -0.942857142857143]]
R:
[[13.999999999999998, 21.00000000000001, -14.000000000000004],
[-5.506706202140776e-16, -175.00000000000003, 70.0],
[3.0198066269804245e-16, -3.552713678800501e-14, 35.000000000000014]]
但我只能让 Q 正常工作。