Conditional within align environment not resolving

I try to use a shortcut for setting matrices with different brackets. My solution works fine in displaymath and equation environments. However, as soon as I try to use it within align, there is an error coming up.

Does anyone know a solution where I can still use my definition within align?

\documentclass{scrreprt}

\usepackage{amsmath}

\newcommand{\Mtrx}[2][1]{
\ifx0#1
\begin{matrix}  #2 \end{matrix}
\else\ifx1#1
\begin{bmatrix}  #2 \end{bmatrix}
\else\ifx2#1
\begin{pmatrix}  #2 \end{pmatrix}
\fi\fi\fi
}

\begin{document}
% everything as expected here:
$$\Mtrx[2]{A & B \\ C & D} = \Mtrx[1]{c\\d}$$

% The following align-equation gives an error:
\begin{align}
\Mtrx[2]{A & B \\ C & D} &= 0
\end{align}

\end{document}

• welcome to tex.se! error is cause by use of ampersands. try \begin{align} {\Mtrx[2]{A & B \\ C & D}} &= 0 \end{align}  ... – Zarko Dec 7 at 13:58

You solve the issue by simply adding braces in the definition of \Mtrx:

\newcommand{\Mtrx}[2][1]{{% <--- brace
\ifx0#1
\begin{matrix}  #2 \end{matrix}
\else\ifx1#1
\begin{bmatrix}  #2 \end{bmatrix}
\else\ifx2#1
\begin{pmatrix}  #2 \end{pmatrix}
\fi\fi\fi
}} % <--- brace


However, here's how I'd do:

\documentclass{scrreprt}

\usepackage{amsmath}

\newcommand{\Mtrx}[2][]{%
\begin{#1matrix} #2 \end{#1matrix}
}

\begin{document}

$$\Mtrx[p]{A & B \\ C & D} = \Mtrx[b]{c\\d}$$

\begin{align}
\Mtrx[p]{A & B \\ C & D} &= 0
\end{align}

\end{document}


If you really prefer numbers,

\documentclass{scrreprt}

\usepackage{amsmath}

\newcommand{\Mtrx}[2][0]{%
\begin{\mtrxtype{#1}matrix} #2 \end{\mtrxtype{#1}matrix}
}
\newcommand{\mtrxtype}[1]{%
\ifcase#1\or b\or p\fi
}

\begin{document}

$$\Mtrx[2]{A & B \\ C & D} = \Mtrx[1]{c\\d}$$

\begin{align}
\Mtrx[2]{A & B \\ C & D} &= 0
\end{align}

\end{document}


error is caused by use of ampersands. these from your new command had to be some how hidden from align ones. for example try

\begin{align}
{\Mtrx[2]{A & B \\ C & D}} &= 0
\end{align}


or redefine your command as follows:

\documentclass{scrreprt}

\usepackage{amsmath}

\newcommand{\Mtrx}[2][1]{
\ifx 0#1
{\begin{matrix}  #2 \end{matrix}}
\else\ifx 1#1
{\begin{bmatrix}  #2 \end{bmatrix}}
\else\ifx 2#1
{\begin{pmatrix}  #2 \end{pmatrix}}
\fi\fi\fi
}

\begin{document}
% everything as expected here:
$$\Mtrx[2]{A & B \\ C & D} = \Mtrx[1]{c\\d}$$

% The following align-equation gives an error: NOT ANYMORE
\begin{align}
\Mtrx[2]{A & B \\ C & D} &= 0
\end{align}