# How can I check if the matrix is of the following form?

$$\left( \begin{array}{cccccc} -a & 0 & 0 & 0 & 0 & 0 \\ 0 & a & 0 & 0 & 0 & 0 \\ 0 & 0 & -a & 0 & 0 & 0 \\ 0 & 0 & 0 & a & 0 & 0 \\ 0 & 0 & 0 & 0 & -a & 0 \\ 0 & 0 & 0 & 0 & 0 & a \\ \end{array} \right)$$

That is, diagonal matrix with changing sign on the main diagonal.

• Is "a" scalar or is it allowed to be another Matrix? Mar 28, 2023 at 17:10
• @JosephDoggie scalar Mar 28, 2023 at 18:34

If u is the matrix:

DiagonalMatrixQ[u] && AllTrue[Ratios@Diagonal@u, # === -1 &]


would return True for compliant matrices.

• Just pointing out the obvious for OP in case it proves a later pitfall - if OP were unstatedly treating a as strictly positive, this solution will yield True when the first element is positive (unlike your example) Mar 29, 2023 at 8:54
• I checked with u and -u so both cases are covered. Only alternating signs are required. @AntiEarth
– Syed
Mar 29, 2023 at 8:57
• Yep, that's what I'm stating - OP may have had an unstated additional requirement that a is positive (why else start with -a instead of a in their example matrix?). In that scenario, your pattern matches their example matrices (first element negative) but also matches more (first element positive) Mar 29, 2023 at 8:58
• I can work with what's presented and stated. But this is an acute observation. Thanks.
– Syed
Mar 29, 2023 at 9:00

I'm assuming that the matrix can be of any size, and that $$a$$ can stand for anything:

check[u_] := DiagonalMatrixQ[u] &&
Apply[SameQ, Diagonal[u]*(-1)^Range[Length[u]]]

check @ {{-a,  0,  0,  0,  0,  0},
{ 0,  a,  0,  0,  0,  0},
{ 0,  0, -a,  0,  0,  0},
{ 0,  0,  0,  a,  0,  0},
{ 0,  0,  0,  0, -a,  0},
{ 0,  0,  0,  0,  0,  a}}
(*    True    *)

check @ {{-a,  0,  0,  0,  0,  0},
{ 0,  a,  0,  0,  0,  0},
{ 0,  0, -a,  0,  0,  0},
{ 0,  0,  0,  a,  0,  0},
{ 0,  0,  0,  0, -a,  0},
{ 0,  0,  0,  0,  0,  b}}
(*    False    *)

mat = {{-a, 0, 0, 0, 0, 0}, {0, a, 0, 0, 0, 0}, {0, 0, -a, 0, 0,
0}, {0, 0, 0, a, 0, 0}, {0, 0, 0, 0, -a, 0}, {0, 0, 0, 0, 0, a}}

diag = Table[(-1)^n*a, {n, 1, Length@mat}]
(DiagonalMatrix[diag]) === mat

(* True *)