首页 > 解决方案 > Numpy adding values to diagonals

问题描述

I wish to create an NxN numpy array where only everything above the main diagonal is filled. The way it is filled is that the main diagonal (k=0) is filled with gamma**0, the k=1 diagonal is filled with gamma**1, the k=2 diagonal is filled with gamma**2 etc...

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)

This correctly gives

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

I wanted to ask if there were any more simpler or elegant ways of handling this or something different. I will be handling with multidimensial arrays frequently and I wanted to be inspired by different tools and approaches.

标签: pythonnumpymatrixmultidimensional-array

解决方案


一种方法是创建上三角索引,np.triu_indices然后使用高级索引将值分配给这些位置:

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.   ]])

推荐阅读