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]
CodePudding user response:
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])]
CodePudding user response:
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])
]