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

时间:2018-07-09 21:38:07

标签: python matrix vector triangulation

我正在尝试获取相关矩阵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元素都放入其中。希望有人能帮忙!

2 个答案:

答案 0 :(得分:1)

您可以为所需的对角线生成索引数组

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

答案 1 :(得分:0)

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

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