Get indices of matrix from upper triangle

£可爱£侵袭症+ 提交于 2021-02-07 18:29:45

问题


I have a symmetric matrix represented as a numpy array, like the following example:

[[ 1.          0.01735908  0.01628629  0.0183845   0.01678901  0.00990739 0.03326491  0.0167446 ]
 [ 0.01735908  1.          0.0213712   0.02364181  0.02603567  0.01807505 0.0130358   0.0107082 ]
 [ 0.01628629  0.0213712   1.          0.01293289  0.02041379  0.01791615 0.00991932  0.01632739]
 [ 0.0183845   0.02364181  0.01293289  1.          0.02429031  0.01190878 0.02007371  0.01399866]
 [ 0.01678901  0.02603567  0.02041379  0.02429031  1.          0.01496896 0.00924174  0.00698689]
 [ 0.00990739  0.01807505  0.01791615  0.01190878  0.01496896  1.         0.0110924   0.01514519]
 [ 0.03326491  0.0130358   0.00991932  0.02007371  0.00924174  0.0110924  1.          0.00808803]
 [ 0.0167446   0.0107082   0.01632739  0.01399866  0.00698689  0.01514519 0.00808803  1.        ]]    

And I need to find the indices (row and column) of the greatest value without considering the diagonal. Since is a symmetric matrix I just took the the upper triangle of the matrix.

ind = np.triu_indices(M_size, 1)

And then the index of the max value

max_ind = np.argmax(H[ind])

However max_ind is the index of the vector resulting after taking the upper triangle with triu_indices, how do I know which are the row and column of the value I've just found?

The matrix could be any size but it's always symmetric. Do you know a better method to achieve the same? Thank you


回答1:


Couldn't you do this by using np.triu to return a copy of your matrix with all but the upper triangle zeroed, then just use np.argmax and np.unravel_index to get the row/column indices?

Example:

x = np.zeros((10,10))
x[3, 8] = 1
upper = np.triu(x, 1)
idx = np.argmax(upper)
row, col = np.unravel_index(idx, upper.shape)

The drawback of this method is that it creates a copy of the input matrix, but it should still be a lot quicker than looping over elements in Python. It also assumes that the maximum value in the upper triangle is > 0.




回答2:


You can use the value of max_ind as an index into the ind data

max_ind = np.argmax(H[ind])
Out: 23

ind[0][max_ind], ind[1][max_ind],
Out: (4, 6)

Validate this by looking for the maximum in the entire matrix (won't always work -- data-dependent):

np.unravel_index(np.argmax(H), H.shape)
Out: (4, 6)



回答3:


There's probably a neater "numpy way" to do this, but this is what comest to mind first:

answer = None
biggest = 0
for r,row in enumerate(matrix):
    i,elem = max(enumerate(row[r+1:]), key=operator.itemgetter(1))
    if elem > biggest:
        biggest, answre = elem, i


来源:https://stackoverflow.com/questions/21316056/get-indices-of-matrix-from-upper-triangle

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!