Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Acces all off diagonal elements of boolean numpy matrix

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.

like image 756
MaxPowers Avatar asked Aug 04 '14 07:08

MaxPowers


People also ask

How do you find the diagonal elements of a matrix in NumPy?

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.

How do you extract a diagonal matrix?

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.

How do you access the elements of a NumPy matrix?

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.


2 Answers

You need the bitwise not operator:

M[~M]
like image 176
Jaime Avatar answered Sep 23 '22 00:09

Jaime


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)
like image 29
Mark Avatar answered Sep 23 '22 00:09

Mark