-1

I have a 4x4 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]])

Christoph Rackwitz
  • 11,317
  • 4
  • 27
  • 36
wowzer
  • 25
  • 5

1 Answers1

0

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]
Ahmed AEK
  • 8,584
  • 2
  • 7
  • 23
  • Thank you so much! Could you please explain the code? I'm particularly a bit confused about shape[0] and dtype=bool. – wowzer Sep 25 '22 at 23:44
  • @rabeca A1.shape is the shape of the matrix, which is `(4,4)`, the `[0]` is simply getting the first `4`, because this function expect only 1 number not two, as for the`dtype=bool` you can just omit it and the code will work, it just makes this piece of code slightly faster by using smaller size in memory (a boolean instead of float), which doesn't really matter. – Ahmed AEK Sep 25 '22 at 23:53