Python 向对角线添加值的Numpy
我希望创建一个Python 向对角线添加值的Numpy,python,numpy,matrix,multidimensional-array,Python,Numpy,Matrix,Multidimensional Array,我希望创建一个NxNnumpy数组,其中仅填充主对角线上方的所有内容。 填充的方式是主对角线(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) 这是正确的 arra
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. ]])
我想问,是否有更简单或优雅的方式来处理这个问题或其他不同的事情。我将经常处理多维数组,我希望受到不同工具和方法的启发。一种方法是使用创建上三角索引,然后使用该索引为这些位置赋值:
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. ]])
一种方法是使用创建上三角索引,然后使用为这些位置赋值:
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. ]])