Search code examples
pythonarraysnumpymatrixindexing

Generation of values above diagonal numpy array


Suppose you have a 10x10 numpy array of intensity values extracted from an image. The exact numbers do not matter right now. I would like to take this matrix, and generate vertices for a graph using only the vertex locations of the upper half of the matrix. More specifically, if our matrix dimensions are defined as (MxN), we could possibly write something like this:

for x in range(M1,M2,M3...M10):
    for y in range(N1,N2,N3...N10):
       if (x-y) >=0:
           graph.addVertex(x,y)

The graph class definition and addVertex definition are NOT important to me as I already have them written. I am only concerned about a method in which I can only consider vertices which are above the diagonal. Open to any and all suggestions, my suggestion above is merely a starting point that may possibly be helpful. Thanks!

EDIT: SOLUTION

Sorry if my clarity issues were atrocious, as I'm somewhat new to coding in Python, but this is the solution to my issue:

g=Graph()
L=4
outerindex=np.arange(L**2*L**2).reshape((L**2,L**2))
outerindex=np.triu(outerindex,k=0)
for i in range(len(outerindex)):
    if outerindex.any()>0:
        g.addVertex(i)

In this manner, when adding vertices to our newly formed graph, the only new vertices formed will be those that reside in locations above the main diagonal.


Solution

  • I think what you want is something like this:

    import numpy as np
    
    a = np.arange(16).reshape((4,4))
    print a
    
    for i in range(4):
        for j in range(i, 4):
            print a[i,j],
    
    # [[ 0  1  2  3]
    #  [ 4  5  6  7]
    #  [ 8  9 10 11]
    #  [12 13 14 15]]
    
    # 0 1 2 3 5 6 7 10 11 15
    

    That is, the key point here is to make the index of the inner loop dependent on the outer loop.

    If you don't want to include the diagonal, use the inner loop with range(i+1,4).