I am trying to print the diagonal numbers of this matrix so that I get [5, 9, 13, 17, 21]
.
I've tried changing the variables in the for
loop.
matrix = [[ 1, 2, 3, 4, 5],
[ 6, 7, 8, 9, 10],
[11, 12, 13, 14, 15],
[16, 17, 18, 19, 20],
[21, 22, 23, 24, 25]]
diagonal = []
last_column = len(matrix[0]) - 1
for row in matrix:
diagonal.append([row][0][4])
print(diagonal)
Instead of getting the diagonal numbers, I get [5, 10, 15, 20, 25]
.
You can also use numpy.diagonal
import numpy
matrix = [[ 1, 2, 3, 4, 5],
[ 6, 7, 8, 9, 10],
[11, 12, 13, 14, 15],
[16, 17, 18, 19, 20],
[21, 22, 23, 24, 25]]
arr=numpy.array(matrix)
print(numpy.fliplr(arr).diagonal())
Outputs:
[ 5 9 13 17 21]
To get the diagonal use print(arr.diagonal())
You want the anti-diagonal, so you can use a simple list comprehension (assuming matrix
is square).
[matrix[i][-(i+1)] for i in range(len(matrix))]
# [5, 9, 13, 17, 21]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With