Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

How to obtain elements from the matrix above the main diagonal?

Assuming I have a matrix:

m = np.arange(16).reshape((4, 4))            
m

array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11],
       [12, 13, 14, 15]])

And I need to get a list of elements which are above the main diagonal (I don't care about the order as long as it is determined and will not change from call to call), I wrote:

def get_elements_above_diagonal(m):
    for i in range(len(m)):
        for j in range(i + 1, len(m)):
            yield m[i, j]

list(get_elements_above_diagonal(m))
[1, 2, 3, 6, 7, 11]

But then I wondered, may be I am reinventing the wheel here. Is there a simpler way to obtain these elements as a flat list?

click to hide/show revision 2
retagged

How to obtain elements from the matrix above the main diagonal?

Assuming I have a matrix:

m = np.arange(16).reshape((4, 4))            
m

array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11],
       [12, 13, 14, 15]])

And I need to get a list of elements which are above the main diagonal (I don't care about the order as long as it is determined and will not change from call to call), I wrote:

def get_elements_above_diagonal(m):
    for i in range(len(m)):
        for j in range(i + 1, len(m)):
            yield m[i, j]

list(get_elements_above_diagonal(m))
[1, 2, 3, 6, 7, 11]

But then I wondered, may be I am reinventing the wheel here. Is there a simpler way to obtain these elements as a flat list?