Ask Your Question
1

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

asked 2015-02-27 08:31:58 -0500

Eugene gravatar image

updated 2015-09-02 05:32:17 -0500

FrédéricC gravatar image

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?

edit retag flag offensive close merge delete

1 answer

Sort by » oldest newest most voted
1

answered 2015-02-27 11:06:03 -0500

updated 2015-02-27 16:39:12 -0500

Here is a one liner that might be a bit better since the numpy function tolist is optimized:

  sage: sum((m[i,i+1:].tolist() for i in range(4)), [])
  [1, 2, 3, 6, 7, 11]

Vincent

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools

1 follower

Stats

Asked: 2015-02-27 08:31:58 -0500

Seen: 139 times

Last updated: Feb 27 '15