python - 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.
解决方案
一种方法是创建上三角索引,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. ]])
推荐阅读
- javascript - 在javascript中返回没有变异的对象
- wordpress - 在 Hostgator 上注销时,Wordpress 网站主页无法正常工作
- java - 如何将文本文件中的值存储到适当的变量中,以及如何使此代码块更清晰?
- python - 给定图形的边列表(有向),如何找到 2 个节点之间的距离?
- java - Java,找到 182.5 % (365 / 12)
- react-native - 使用反应原生导航从父级访问状态值
- rdma - RDMA:我如何知道轮询 CQ 后是否响应了读取请求?
- docker - Kubectl 始终生成具有相同名称的 pod
- python - 删除两个字符之间的文本而不更改数据类型
- javascript - Javascript - 如何从多选下拉列表中将选择值记录为数组(包括添加和删除)