Python TypeError:'NoneType'对象不可订阅

时间:2015-09-17 05:46:43

标签: python linear-algebra

我正在尝试编写一个函数,它在已经采用梯形形式的矩阵上执行反替代,但每次我尝试访问我的矩阵的索引时,我得到 - TypeError:'NoneType'对象不可订阅。我一直在用这个工作几个小时,但我真的很沮丧,虽然我可能忽略了一个明显的细节。这是我的代码:

def backsubstitution(B):
    """
    return the reduced row echelon form matrix of B
    """
    G = B.copy()
    m, n = np.shape(G)
    pivot = 0
    # To start, let i = 0
    i = 0
    # If row i is all zeros, or if i exceeds the number of rows in A, stop
    while(i != m):
        # If row i has a nonzero pivot value, divide row i by its pivot value to
        # create a 1 in the pivot position
        # First, find the pivot position
        pivPos = 0
        while(G[i][pivPos] == 0.0):
            pivPos += 1
            if(pivPos == n-1 and G[i][pivPos] == 0.0):
                return G
        # Now divide row i by its pivot value if the pivot is not already 1
        if(G[i][pivPos] != 1):
            pivot = G[i][pivPos]
            for k in range(n):
                if(G[i][k] == 0.0):
                    G[i][k] == 0.0
                else:
                    G[i][k] = (G[i][k] / pivot)
        # Use row reduction operations to create zeros in all positions above the
        # pivot
        if(i != 0):
            for l in range(i):
                G = rowReduce(G, i, i-1, pivPos)         
        # Let i = i + 1
        i += 1
    return G

如果有人可以提供帮助,我将非常感激。

编辑:散列注释是我教授给出的后置替代算法的步骤。

第二次编辑:rowReduce是教授提供的功能

3rd Edit:这是rowReduce:

def relError(a, b):
    """
    compute the relative error of a and b
    """
    with warnings.catch_warnings():
        warnings.simplefilter("error")
        try:
            return np.abs(a-b)/np.max(np.abs(np.array([a, b])))
        except:
            return 0.0

def rowReduce(A, i, j, pivot):
    """
    reduce row j using row i with pivot pivot, in matrix A
    operates on A in place
    """
    factor = A[j][pivot] / A[i][pivot]
    for k in range(len(A[j])):
        # we allow an accumulation of error 100 times larger than a single computation
        # this is crude but works for computations without a large dynamic range
        if relError(A[j][k], factor * A[i][k]) < 100 * np.finfo('float').resolution:
            A[j][k] = 0.0
        else:
            A[j][k] = A[j][k] - factor * A[i][k]

我在echelon形式的矩阵M上调用函数: backSub = backsubstitution(M)

1 个答案:

答案 0 :(得分:3)

请注意,rowReduce的文档字符串表示“在适当的位置”。这意味着它更改你传递的数组,而不是给你一个新的。如果没有明确记录,另一个重要指标是缺少任何return语句。

这意味着这一行:

G = rowReduce(G, i, i-1, pivPos)

应该是:

rowReduce(G, i, i-1, pivPos)

由于rowReduce没有返回新数组(或者确实显式return),因此其返回值为None。当您将结果重新分配回G时,当您返回到循环顶部并尝试执行此操作时,它将为None

G[i][pivPos]

这将为您提供TypeError