24n8
24n8

Reputation: 2236

Getting diagonal of a matrix in numpy and excluding an element

I am trying to get the diagonal elements of a matrix, excluding one diagonal element. If I want the full diagonal elements, I know I can simply do A.numpy.diagonal() where A is a numpy square matrix to get the full array of diagonal elements. But I don't want A[i][i] for some i. So obviously I can delete the element corresponding to i from the output of A.numpy.diagonal(). But I think this is slower than using slicing? How would one use slicing on this problem to get all the diagonal elements excluding the component at A[i][i]?

Upvotes: 2

Views: 3238

Answers (1)

user3483203
user3483203

Reputation: 51165

You can achieve the same behavior as diagonal by just using arange for rows and columns. Remove the index you aren't interested in before indexing (as @hpaulj noted in the comments, practically it's faster just to find the diagonal and remove the index afterwards):


Setup

a = np.arange(25).reshape(5,5)
i = 3     # exclude the diagonal element at index 3

array([[ 0,  1,  2,  3,  4],
       [ 5,  6,  7,  8,  9],
       [10, 11, 12, 13, 14],
       [15, 16, 17, 18, 19],
       [20, 21, 22, 23, 24]])

d = np.arange(a.shape[0])
m = np.delete(d, i)

a[m, m]

array([ 0,  6, 12, 24])

Upvotes: 3

Related Questions