将三角矩阵的元素放入向量中

Put elements of a triangular matrix in a vector

我正在尝试获取相关矩阵 mS 的上对角线元素。因此,为此我使用 np.triu(我不想在对角线上使用它们,所以我使用 k=1)。但是,我想将这些元素放在一个向量中。我已经阅读了很多关于 np.triu_indices 的文章,但是代码不起作用,因为我收到错误:具有多个元素的数组的真值不明确。使用 a.any() 或 a.all()

mS= [[1, .8, .6, .8, .7, .8, .6, .9, .5, .6, .8], 
     [.8, 1, .8, .5, .6, .7, .7, .8, .5, .8, .7], 
     [.6, .8, 1, .7, .8, .6, .7, .6, .7, .7, .9], 
     [.8, .5, .7, 1, .8, .6, .8, .7, .6, .9, .8], 
     [.7, .6, .8, .8, 1, .5, .8, .9, .9, .8, .6], 
     [.8, .7, .6, .6, .5, 1, .9, .7, .5, .9, .8], 
     [.6, .7, .7, .8, .8, .9, 1, .6, .8, .7, .7], 
     [.9, .8, .6, .7, .9, .7, .6, 1, .8, .6, .9], 
     [.5, .5, .7, .6, .9, .5, .8, .8, 1, .9, .8], 
     [.6, .8, .7, .9, .8, .9, .7, .6, .9, 1, .8], 
     [.8, .7, .9, .8, .6, .8, .7, .9, .8, .8, 1]]
mS= np.array(mS)

mSi= np.triu(mS, k=1).

# Show mSi
mSi = array([[0. , 0.8, 0.6, 0.8, 0.7, 0.8, 0.6, 0.9, 0.5, 0.6, 0.8],
   [0. , 0. , 0.8, 0.5, 0.6, 0.7, 0.7, 0.8, 0.5, 0.8, 0.7],
   [0. , 0. , 0. , 0.7, 0.8, 0.6, 0.7, 0.6, 0.7, 0.7, 0.9],
   [0. , 0. , 0. , 0. , 0.8, 0.6, 0.8, 0.7, 0.6, 0.9, 0.8],
   [0. , 0. , 0. , 0. , 0. , 0.5, 0.8, 0.9, 0.9, 0.8, 0.6],
   [0. , 0. , 0. , 0. , 0. , 0. , 0.9, 0.7, 0.5, 0.9, 0.8],
   [0. , 0. , 0. , 0. , 0. , 0. , 0. , 0.6, 0.8, 0.7, 0.7],
   [0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0.8, 0.6, 0.9],
   [0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0.9, 0.8],
   [0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0.8],
   [0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. ]])

 vPR= np.triu_indices(mS, -55)
 This gives me the error 

我想要一个数组(名为 vPR),其中放置了上面的所有 triu 元素。希望有人能帮忙!

函数np.triu_indices 为您提供了对角线上所有项目的索引列表。从三角矩阵开始,trim 左列和底行(因为它们包含全零),并通过索引提取所有其他项目:

np.triu(mS, k=1)[:-1, 1:][np.triu_indices(mS.shape[0] - 1)]
#array([ 0.8,  0.6,  0.8,  0.7,  0.8,  0.6,  0.9,  0.5,  0.6,  0.8,  0.8,
#        0.5,  0.6,  0.7,  0.7,  0.8,  0.5,  0.8,  0.7,  0.7,  0.8,  0.6...

您可以为您想要的对角线生成索引数组

r, c = mSi.shape

mSi[np.arange(0, r-1), np.arange(1, c)]

Out[28]: array([0.8, 0.8, 0.7, 0.8, 0.5, 0.9, 0.6, 0.8, 0.9, 0.8])