# Comparing two matrices in an If block

I want to find out for what value of n MatrixPower[u, n] == IdentityMatrix

u = {{0, 0, I}, {-I, 0, 0}, {0, -1, 0}};
n = 1;
While[n < 10,
If[{MatrixPower[u, n] == IdentityMatrix}, Print["TRUTH"]]; n++]


I chose n=10 because I know the answer is 6, but it doesn't print 6. What is the problem here?

u = {{0, 0, I}, {-I, 0, 0}, {0, -1, 0}};

soln = Solve[
{MatrixPower[u, n] == IdentityMatrix,
n > 0}, n][]

(*  {n -> ConditionalExpression[-6 C,
C ∈ Integers && C <= -1]}  *)


Verifying the solution

Assuming[{Element[C, Integers], C <= -1},
MatrixPower[u, n] == IdentityMatrix /. soln // FullSimplify]

(*  True  *)


Or for specific values

And @@ Table[
MatrixPower[u, n] == IdentityMatrix,
{n, 6, 72, 6}]

(*  True  *)


Consider this illustrative example:

x = 2;
If[{x > 0}, Print["positive"]]


If[{True}, Print["positive"]]

The thing is, the first argument of If should yield True or False; in the above example, it yields {True}, which due to the curly brackets is different than True. Hence one should type

If[x > 0, Print["positive"]]


positive

So the reason why the OP's syntax doesn't give anything are the brackets which should be removed:

u = {{0, 0, I}, {-I, 0, 0}, {0, -1, 0}};
n = 1;
While[n < 10,
If[MatrixPower[u, n] == IdentityMatrix, Print["TRUTH"]]; n++]


TRUTH

But "it doesn't print 6", so let's modify the Print part:

While[n < 10,
If[MatrixPower[u, n] == IdentityMatrix,
Print["TRUTH for n=" <> ToString[n]]]; n++]


TRUTH for n=6

The problem with the above syntax is that n = 1 has to be set at each evaluation of the While cell; if it's not, n is assigned a value of 10. To avoid this, use Block which makes n local for the While:

Block[{n = 1},
While[n < 10,
If[MatrixPower[u, n] == IdentityMatrix,
Print["TRUTH for n=" <> ToString[n]]]; n++]
]


TRUTH for n=6