Search code examples
pythonadjacency-matrix

Traversing the upper triangle of a matrix in Python


Suppose there exists a matrix M (could be either stored using numpy arrays or DataFrames) and one wants to obtain a list of tuples (r,c,v) for all entrys in the upper triangle of M excluding the main diagonal, such that r is the row index, c is the column index and v is the value in M indexed by r and c.

Reading different questions I have learned so far that I can build a triangular indexer using np.triu_indices or similiar functions, but that makes me loose the information of what indices correspond to a given value. E.g, in Get indices of matrix from upper triangle this is discussed for the maximum value of a matrix, but I have trouble generalizing this to get a list of all values as defined above.


Solution

  • The values in the upper triangle of a square matrix excluding the main diagonal are all values, where the column index is greater than the row index:

    import numpy as np
    
    M = np.array([[10, 11, 12, 13],
                  [14, 15, 16, 17],
                  [18, 19, 20, 21],
                  [22, 23, 24, 15]])
    
    for r in range(M.shape[0]):
        for c in range(r + 1, M.shape[0]):
            v = M[r, c]
            print(r, c, v)