乘法矩阵的麻烦

时间:2013-06-19 23:28:38

标签: python list linear-algebra

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

我不确定为什么因为乘法函数本身适用于标准乘法...如果有人可以提供帮助,请提前感谢!

编辑:我添加了一个return语句来转置,是的,它实际上给了一个转置矩阵。似乎繁衍是罪魁祸首。这是它应该做的:

 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正常工作。

2 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:1)

目前看来你的transpose()函数仍然会返回一个None类型,如果你仍然得到相同的错误,并且在你的转置中你返回转置但从未定义它。也许这是一个错字?