Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Non diagonal elements of a matrix to 0

What is the quickest way to convert the non-diagonal elements of a square symmetrical numpy ndarray to 0?

like image 233
Prgmr Avatar asked Dec 05 '17 07:12

Prgmr


People also ask

When the non diagonal elements are zero it is called?

The correct option is B 0. A diagonal matrix is a matrix in which all the elements other than the diagonal are zero. Hence, all the non diagonal elements of a diagonal matrix are 0. Suggest Corrections. 0.

How do you find non diagonal elements in a matrix?

The elements which do not lie on the leading diagonal of a square matrix is called non-diagonal elements of the matrix. The number of rows is equal to the number of columns in a square matrix. So, a principal diagonal is formed by the first element of first row and last element of last row.

Can the diagonal of a diagonal matrix be zero?

A diagonal matrix is defined as a square matrix in which all off-diagonal entries are zero. (Note that a diagonal matrix is necessarily symmetric.) Entries on the main diagonal may or may not be zero. If all entries on the main diagonal are equal scalars, then the diagonal matrix is called a scalar matrix.


2 Answers

I'd check out the speed of saving the diagonal away, then zap the matrix, then restore the diagonal:

n = len(mat)
d = mat.ravel()[::n+1]
values = d.copy()
mat[:,:] = 0
d[:] = values

if the matrix is not huge may be however that just allocating a new one is faster

mat = numpy.diag(numpy.diag(mat))
like image 87
6502 Avatar answered Sep 20 '22 05:09

6502


Here is a solution that also works on non-contiguous arrays:

a = np.arange(110).reshape(10, 11)[:, :10]

diag = np.einsum('ii->i', a)
# or if a is not guaranteed to be square
# mn = min(a.shape)
# diag = np.einsum('ii->i', a[:mn, :mn])
save = diag.copy()
a[...] = 0
diag[...] = save

a

# array([[  0,   0,   0,   0,   0,   0,   0,   0,   0,   0],
#        [  0,  12,   0,   0,   0,   0,   0,   0,   0,   0],
#        [  0,   0,  24,   0,   0,   0,   0,   0,   0,   0],
#        [  0,   0,   0,  36,   0,   0,   0,   0,   0,   0],
#        [  0,   0,   0,   0,  48,   0,   0,   0,   0,   0],
#        [  0,   0,   0,   0,   0,  60,   0,   0,   0,   0],
#        [  0,   0,   0,   0,   0,   0,  72,   0,   0,   0],
#        [  0,   0,   0,   0,   0,   0,   0,  84,   0,   0],
#        [  0,   0,   0,   0,   0,   0,   0,   0,  96,   0],
#        [  0,   0,   0,   0,   0,   0,   0,   0,   0, 108]])
like image 41
Paul Panzer Avatar answered Sep 21 '22 05:09

Paul Panzer