【问题标题】:Don't understand this IndexError using numpy不理解这个 IndexError 使用 numpy
【发布时间】:2019-01-19 14:56:30
【问题描述】:

给我一​​个二次矩阵,必须做如下:

For each entry (i,j) in the matrix
    If i = j:
        set y[i,j] = x[i,j].
    Else:
        set y[i,j] = x[i,j] + x[j,i]

我制作了以下脚本:

def symmetrize(x):

    ## The symmetrized matrix that is returned
    y = np.zeros(np.shape(x))

    ## For loop for each element (i,j) in the matrix
    for i in range (np.size(x)):
        for j in range (np.size(x)):
            if i == j:
                y[i,j] = x[i,j]
            else:
                y[i,j] = x[i,j] + x[j,i]
    return y

每当我想使用以下矩阵运行代码时都会收到此错误消息:

np.array([[1.2, 2.3, 3.4],[4.5, 5.6, 6.7], [7.8, 8.9, 10.0]])

错误信息:

y[i,j] = x[i,j] + x[j,i]

IndexError: index 3 is out of bounds for axis 1 with size 3

有人知道问题出在哪里吗?

【问题讨论】:

    标签: python numpy matrix symmetric


    【解决方案1】:

    np.size(),没有轴,为您提供矩阵中的元素总数。所以你的range()s 将从 0 到 8,而不是从 0 到 2。

    您不需要为此使用np.size()np.shape();这些功能甚至不再在文档中列出。只需使用矩阵的.shape 属性:

    y = np.zeros(x.shape)
    
    for i in range(x.shape[0]):
        for j in range(x.shape[1]):
    

    有更好的方法来产生你的输出。你可以使用:

    def symmetrize(x):
        return x + x.T - np.diag(x.diagonal())
    

    相反。 x.T转置 矩阵,因此行和列交换了。 x + x.T是原矩阵和转置矩阵之和,所以对角线上的数字加倍。 x.diagonal() 是一个仅由对角线上的数字组成的数组,一旦你在对角线上创建了这些数字的矩阵,就可以将其减去,这就是 np.diag() 为你所做的。

    【讨论】:

    • 很高兴能帮上忙!如果您觉得它对您有用,请随时 accept my answer。 :-)
    【解决方案2】:

    您以错误的方式使用np.size(),它不会告诉您列表有多少行或列,而是数组中的元素数,在您的情况下 - 9。您可以像这样使用列表的形状:

    def symmetrize(x):
    
        ## The symmetrized matrix that is returned
        y = np.zeros(np.shape(x))
    
        ## For loop for each element (i,j) in the matrix
        for i in range(x.shape[0]):
            for j in range(x.shape[1]):
                if i == j:
                    y[i,j] = x[i,j]
                else:
                    y[i,j] = x[i,j] + x[j,i]
        return y
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-12-27
      • 1970-01-01
      • 2019-09-18
      • 1970-01-01
      • 1970-01-01
      • 2021-05-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多