What is the quickest way to convert the non-diagonal elements of a square symmetrical numpy ndarray to 0?
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.
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.
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.
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))
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]])
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