# Error when pmatrix/array is inside \ifcase

The following example produces an incomprehensible error:

\documentclass[letterpaper,12pt]{exam}

\usepackage{amsmath}
\usepackage{amsfonts}
\usepackage{graphicx}

\begin{document}
We are interested in the following matrix:
\begin{gather*}
\ifcase 0 \relax
C = \begin{pmatrix}  1 &  2 \\  1 & -2 \end{pmatrix}
\or
C = \begin{pmatrix}  3 &  4 \\  1 & -5 \end{pmatrix}
\fi
\end{gather*}
\end{document}


What is going on here? It works fine if I replace by the matrices by anything else, so I presume it is the interaction of the pmatrix environment with the ifcases.

The problem persists if pmatrix is replaced by the more foundational array.

\documentclass[letterpaper,12pt]{exam}

\usepackage{amsmath}
\usepackage{amsfonts}
\usepackage{graphicx}

\begin{document}
We are interested in the following matrix:
\begin{gather*}
\ifcase 0 \relax
C = \begin{array}{cc}  1 &  2 \\  1 & -2 \end{array}
\or
C = \begin{array}{cc}  3 &  4 \\  1 & -5 \end{array}
\fi
\end{gather*}
\end{document}

• The arrays would have to become \begin{array}{cc} or so but this is not essential. – user194703 May 15 at 18:55

If you put braces, it works.

\documentclass[letterpaper,12pt]{article}

\usepackage{amsmath}
\usepackage{amsfonts}
\usepackage{graphicx}

\begin{document}
We are interested in the following matrix:
\begin{gather*}
\ifcase 0 \relax
{ C = \begin{pmatrix}  1 &  2 \\  1 & -2 \end{pmatrix} }
\or
{ C = \begin{pmatrix}  3 &  4 \\  1 & -5 \end{pmatrix} }
\fi
\end{gather*}
\end{document}


The problem are the &; you can solve it by bracing the entries, but there's a possibly better way:

\documentclass[letterpaper,12pt]{exam}
\usepackage{amsmath}
\usepackage{xparse}

\ExplSyntaxOn

\NewDocumentCommand{\docases}{mm}
{
\int_case:nn { #1 } { #2 }
}

\ExplSyntaxOff

\begin{document}

\newcommand{\caseexam}{1}

We are interested in the following matrix:
\begin{gather*}
\docases{\caseexam}
{
{1}{C = \begin{pmatrix}  1 &  2 \\  1 & -2 \end{pmatrix}}
{2}{C = \begin{pmatrix}  3 &  4 \\  1 & -5 \end{pmatrix}}
}
\end{gather*}

\renewcommand{\caseexam}{2}

We are interested in the following matrix:
\begin{gather*}
\docases{\caseexam}
{
{1}{C = \begin{pmatrix}  1 &  2 \\  1 & -2 \end{pmatrix}}
{2}{C = \begin{pmatrix}  3 &  4 \\  1 & -5 \end{pmatrix}}
}
\end{gather*}

\end{document}


Of course you'd set the \caseexam macro only once. Variations on the theme are possible.