Search code examples
pythonnumpymatrix

Get indices of matrix from upper triangle


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


Solution

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