Suppose there is a diagonal matrix M:
#import numpy as np
M = np.matrix(np.eye(5, dtype=bool))
Does anybody know a simple way to access all off diagonal elements, meaning all elements that are False
? In R
I can simply do this by executing
M[!M]
Unfortunately this is not valid in Python.
diag() To Extract Diagonal. Numpy diag() function is used to extract or construct a diagonal 2-d array. It contains two parameters: an input array and k , which decides the diagonal, i.e., k=0 for the main diagonal, k=1 for the above main diagonal, or k=-1 for the below diagonal.
D = diag( v ) returns a square diagonal matrix with the elements of vector v on the main diagonal. D = diag( v , k ) places the elements of vector v on the k th diagonal. k=0 represents the main diagonal, k>0 is above the main diagonal, and k<0 is below the main diagonal.
You can access an array element by referring to its index number. The indexes in NumPy arrays start with 0, meaning that the first element has index 0, and the second has index 1 etc.
You need the bitwise not operator:
M[~M]
You might try np.extract combined with np.eye. For example:
M = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
np.extract(1 - np.eye(3), M)
# result: array([2, 3, 4, 6, 7, 8])
In your example it's almost an identity:
M = np.matrix(np.eye(5, dtype=bool))
np.extract(1 - np.eye(5), M)
#result:
array([False, False, False, False, False, False, False, False, False,
False, False, False, False, False, False, False, False, False,
False, False], dtype=bool)
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