[英]numpy/scipy: fill upper triangle of array with elements of 1d vector?
Say I have a flattened 1D vector that exactly corresponds to the upper triangle elements of a 2D array. 假设我有一个扁平化的1D向量,它与2D数组的上三角元素完全对应。
The 1D vector needs to be read into the upper triangle. 需要将1D向量读入上三角。
I might do the following in python: 我可能会在python中执行以下操作:
triu_flat = ...
row,col = np.triu_indices(50)
D = np.zeros((50,50))
i=0
for r in row:
for c in col:
D[r,c] = triu_flat[i]
i++
However, there must be a way to do this via numpy/scipy operations. 但是,必须有一种通过numpy / scipy操作执行此操作的方法。
You can simply use the indices returned by triu_indices()
, no need for a for
loop: 您可以简单地使用triu_indices()
返回的索引,而无需for
循环:
import numpy
data = numpy.arange(6)
out = numpy.zeros((3, 3))
inds = numpy.triu_indices(len(out))
out[inds] = data
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.