Counter example for a matrix $A^3=A$ but $\mbox{rank}(A) \neq \mbox{tr}(A^2)$ If $A$ is diagonalizable then $\mbox{rank}(A) =  \mbox{tr}(A^2)$.
How to find a counter example for a matrix $A^3=A$ but $\mbox{rank}(A) \neq  \mbox{tr}(A^2)$

There is not any counterexample, regardless of the underlying field or whether $A$ is diagonalisable. When $A^3=A$, $\operatorname{rank}(A)$ must be equal to $\operatorname{tr}(A^2)$. (When the field has characteristic $p>0$, this identity should be understood as one over $\mathbb F$. That is, we actually mean $\varphi(\operatorname{rank}(A))=\operatorname{tr}(A^2)$ where $\varphi$ is the ring homomorphism between $\mathbb Z$ and $\mathbb F$.)
Denote the underlying field by $\mathbb F$ and let $A$ be $n\times n$. Since $(x^2-1)x$ is an annihilating polynomial of $A$ and $x^2-1,x$ are relatively prime, $\mathbb F^n = \ker((A^2-I)A) = \ker(A^2-I)\oplus\ker(A)$. Also, as $A^2-I$ and $A$ commute with $A$, both $\ker(A^2-I)$ and $\ker(A)$ are invariant subspaces of $A$. Therefore
\begin{aligned}
\operatorname{tr}(A^2)
&= \operatorname{tr}(A^2|_{\ker(A^2-I)}) + \operatorname{tr}(A^2|_{\ker(A)})\\
&= \operatorname{tr}(A^2|_{\ker(A^2-I)})\\
&= \operatorname{tr}(I|_{\ker(A^2-I)}) \quad(\because A^2=I \text{ on } \ker(A^2-I))\\
&= \dim\ker(A^2-I) \quad\text{(we mean $\varphi(\dim\ker(\cdots))=\operatorname{tr}(\cdots)$ here)}\\
&= n - \dim\ker(A) \quad(\because \mathbb F^n=\ker(A^2-I)\oplus\ker(A))\\
&= \operatorname{rank}(A).
\end{aligned}
