Python 类型错误:'NoneType'对象不可下标



我正试图编写一个函数,在矩阵上执行反向替换已经在梯级形式,但每次我试图访问我的矩阵的索引,我得到- 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是教授提供的函数

第三次编辑:这里是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]

我调用矩阵M上的函数已经是阶梯形了:backSub = backsubstitution(M)

注意,rowReduce的文档字符串说它"在适当的地方运行"。这意味着它更改您传递给它的数组,而不是返回一个新数组。如果没有明确记录,另一个重要的指示是它缺少任何return语句。

这意味着这一行:

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

应该是:

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

由于rowReduce不返回一个新的数组(或确实显式地return),它的返回值将是None。当你将结果重新赋值给G时,当你回到循环的顶部并尝试这样做时,它将是None:

G[i][pivPos]

这将给你你看到的TypeError

相关内容

  • 没有找到相关文章

最新更新