\iffmode seems to fail for the first token in every matrix cell. Here is a minimal working example.
\documentclass[margin=5mm]{standalone}
\usepackage{mathtools}
\newcommand{\foo}{%
\ifmmode A%
\else B%
\fi%
}
\begin{document}
\foo\foo\foo\
$
\begin{matrix}
\foo\foo\foo& x\foo\\
\foo&x\\
\end{matrix}
$
\end{document}
What I expect it to output is this

Yet, it outputs this

How should I solve this problem?
\relax\ifmmodeinstead. – Skillmon Aug 16 '19 at 15:49