Y4RD13
Y4RD13

Reputation: 984

Getting all diagonals from top right to bottom left in array

I am trying to store all the diagonals in the matrix from the top right to the bottom left and store them in an array.

matrix = array([[2, 0, 0, 2],
                [3, 0, 0, 3],
                [3, 0, 0, 2],
                [0, 0, 0, 0]])

Expected ouptut

[
 [2],
 [0, 3],
 [0, 0, 2],
 [2, 0, 0, 0],
 [3, 0, 0],
 [3, 0],
 [0]
]

What I tried to do was this code: However, this will get me all the diagonals from top left to bottom right

def get_diags_lower_left(matrix):
    return [np.fliplr(matrix).diagonal(i) for i in range(-3, 4)][::-1]

Upvotes: 2

Views: 267

Answers (2)

ImSo3K
ImSo3K

Reputation: 872

A more generalized solution that works on any MxN matrix:

[matrix.diagonal(i) for i in range(-matrix.shape[0] + 1, matrix.shape[1])][::-1]

output:

[array([2]),
 array([0, 3]),
 array([0, 0, 2]),
 array([2, 0, 0, 0]),
 array([3, 0, 0]),
 array([3, 0]),
 array([0])]

Upvotes: 2

Jan Willem
Jan Willem

Reputation: 1094

If you do not flip the matrix it works. Using:

def get_diags_lower_left(matrix):
    return [matrix.diagonal(i) for i in range(-3, 4)][::-1]

Will yield:

[array([2]),
 array([0, 3]),
 array([0, 0, 2]),
 array([2, 0, 0, 0]),
 array([3, 0, 0]),
 array([3, 0]),
 array([0])
]

Upvotes: 2

Related Questions