Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NumPy - Sum of the elements on the secondary diagnoal of a 2D matrix

How can I get the sum of the elements on the secondary diagonal of a matrix? numpy.trace seems to only return main diagonals, and numpy.diagonal doesn't seem to help out with secondary diagonal either.

like image 489
confused00 Avatar asked Sep 17 '25 18:09

confused00


1 Answers

You could always just flip the array a (top to bottom) and use np.trace:

a[::-1].trace()
like image 167
Alex Riley Avatar answered Sep 20 '25 08:09

Alex Riley