乘法矩阵的麻烦



我正在尝试为可选作业进行一些 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 正常工作。

你在transpose()中没有return,所以你返回None 。所以你正在做Q_transpose = None.

就目前而言,如果您仍然收到相同的错误,您的 transpose(( 函数仍然返回 None 类型,并且在转置中您返回转置但从未定义它。也许这是一个错字?

相关内容

  • 没有找到相关文章

最新更新