代码之家  ›  专栏  ›  技术社区  ›  piccolo

Numpy向对角线添加值

  •  1
  • piccolo  · 技术社区  · 6 年前

    我想创造一个 NxN numpy 只填充主对角线上的所有内容的数组。 它的填充方式是主对角线( k=0 )充满了 gamma**0 ,和 k=1 对角线填充 gamma**1 ,和 k=2 对角线填充 gamma**2 等。。。

    gamma = 0.9
    dim = 4
    
    M = np.zeros((dim,dim))
    for i in range(dim)[::-1]:   
        M += np.diagflat([gamma**(dim-i-1)]*(i+1),dim-i-1) 
    
    print(M)
    

    这正确地给出了

    array([[ 1.   ,  0.9  ,  0.81 ,  0.729],
           [ 0.   ,  1.   ,  0.9  ,  0.81 ],
           [ 0.   ,  0.   ,  1.   ,  0.9  ],
           [ 0.   ,  0.   ,  0.   ,  1.   ]])
    

    我想问是否有更简单或优雅的方式来处理这个或其他的事情。我将经常处理多维数组,我希望受到不同工具和方法的启发。

    1 回复  |  直到 6 年前
        1
  •  4
  •   akuiper    6 年前

    一种方法是使用 np.triu_indices 然后使用 advanced indexing 为这些位置赋值:

    M = np.zeros((dim,dim))
    
    rowidx, colidx = np.triu_indices(dim)
    # the diagonal offset can be calculated by subtracting the row index from column index
    M[rowidx, colidx] = gamma ** (colidx - rowidx) 
    
    M
    #array([[ 1.   ,  0.9  ,  0.81 ,  0.729],
    #       [ 0.   ,  1.   ,  0.9  ,  0.81 ],
    #       [ 0.   ,  0.   ,  1.   ,  0.9  ],
    #       [ 0.   ,  0.   ,  0.   ,  1.   ]])