What is an alternative to retrieving diagonal elements without looping or calling np.diag()?

Question:

I have a 4×4 array, A1, and need to retrieve its diagonal elements without looping or calling np.diag(). What’s a way of doing so? Appreciate your help!

A1 = np.array([ [1, 4, 6, 8],[2, 5, 7, 10],[3, 6, 9, 13], [11, 12, 16, 0]])

Asked By: rabeca

||

Answers:

by indexing using the indices of the diagonal, which are the indices of the non-zeros of an identity matrix.

import numpy as np

A1 = np.array([ [1, 4, 6, 8],[2, 5, 7, 10],[3, 6, 9, 13], [11, 12, 16, 0]])
diag_pos = np.eye(A1.shape[0],dtype=bool).nonzero()
print(A1[diag_pos])
[1 5 9 0]
Answered By: Ahmed AEK
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.