3
$\begingroup$

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.
$\endgroup$
4
  • 2
    $\begingroup$ You can used AnyTrue[Abs[Diagonal[m]], Positive] $\endgroup$
    – yarchik
    Aug 19, 2021 at 22:46
  • 2
    $\begingroup$ Another possibility Norm[Diagonal[m]] > 0 or Positive[Norm[Diagonal[m]]] $\endgroup$
    – yarchik
    Aug 19, 2021 at 22:48
  • $\begingroup$ Or, Times @@ Diagonal[m] != 0. I am sure there are several other ways, as well. $\endgroup$
    – bbgodfrey
    Aug 19, 2021 at 23:26
  • $\begingroup$ like the first option, but i like it because of how close it is to the english phrasing: AnyTrue[Diagonal[m], Not@*EqualTo[0]] $\endgroup$
    – thorimur
    Aug 20, 2021 at 1:33

2 Answers 2

3
$\begingroup$
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

$\endgroup$
1
$\begingroup$
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}*)
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.