# Check an input matrix M contains any nonzero diagonal matrix element or not

Is there a way to easily check an input matrix M contains any nonzero diagonal matrix element or not?

For example,

• if the M contains any nonzero diagonal matrix element, Output: True.

• if the M contains all zero diagonal matrix elements, Output: False.

Here are some related built-in functions that may help. But I did not find an exact built-in function that I need.

DiagonalMatrix[list]
gives a matrix with the elements of list on the leading diagonal, and 0 elsewhere.

DiagonalMatrix[list,k]
gives a matrix with the elements of list on the k\[Null]^th diagonal.

DiagonalMatrix[list,k,n]
pads with 0s to create an n*n matrix.

Diagonal[m]
gives the list of elements on the leading diagonal of the matrix m.

Diagonal[m,k]
gives the elements on the k\[Null]^th diagonal of m.
• You can used AnyTrue[Abs[Diagonal[m]], Positive] Aug 19, 2021 at 22:46
• Another possibility Norm[Diagonal[m]] > 0 or Positive[Norm[Diagonal[m]]] Aug 19, 2021 at 22:48
• Or, Times @@ Diagonal[m] != 0. I am sure there are several other ways, as well. Aug 19, 2021 at 23:26
• like the first option, but i like it because of how close it is to the english phrasing: AnyTrue[Diagonal[m], Not@*EqualTo[0]] Aug 20, 2021 at 1:33

p = {{-1, 1, 1}, {2, 0, 2}, {3, 3, 1}};

q = {{0, 1, 1}, {2, 0, 2}, {3, 3, 0}};

1.

Using AllTrue with PossibleZeroQ

! AllTrue[Diagonal @ p, PossibleZeroQ]

True

! AllTrue[Diagonal @ q, PossibleZeroQ]

False

2.

Using ContainsOnly

! ContainsOnly[Diagonal @ p, {0}]

True

! ContainsOnly[Diagonal @ q, {0}]

False

p = {{-1, 1, 1}, {2, 0, 2}, {3, 3, 1}};

q = {{0, 1, 1}, {2, 0, 2}, {3, 3, 0}};

Grabbing the @eldo's examples and using Position:

f = Length@Position[Diagonal@#, 0] != Length@# &;

f /@ {p, q}

(*{True, False}*)