# Using a macro with ifx inside of a bmatrix

The following code does not compile if I don't have the extra braces around the entries of the matrix, and I don't know why. Can I modify \switcher to obviate the need for these extra braces?

\documentclass{article}
\usepackage{amsmath}

\newcommand{\switcher}[2][]
{
\ifx&#1&%
#2
\else
#1
\fi
}

\begin{document}

$\begin{bmatrix} {\switcher{2}} \\ {\switcher[1]{2}} \end{bmatrix}$

\end{document}

• What is switcher supposed to do exactly? – Werner Dec 18 '13 at 2:54
• I only used switcher as a simple example of a function whose behavior changes depending on whether or not the optional argument is specified. My actual function does something different obviously, but I thought the details distracted from the question. – Stirling Dec 18 '13 at 4:23

If you're attempting to condition between whether or not the optional argument is empty, the following is a better approach:

\documentclass{article}
\usepackage{amsmath}% http://ctan.org/pkg/amsmath

\makeatletter
\def\ifemptyarg#1{%
\if\relax\detokenize{#1}\relax % https://tex.stackexchange.com/q/308/5764
\expandafter\@firstoftwo
\else
\expandafter\@secondoftwo
\fi}
\makeatother

\newcommand{\switcher}[2][]{%
\ifemptyarg{#1}
{#2}% Empty optional argument
{#1}% Non-empty optional argument
}

\begin{document}

$\begin{bmatrix} \switcher{2} \\ \switcher[1]{2} \end{bmatrix} \qquad \begin{bmatrix} \switcher{a} & \switcher[b]{c} & \switcher[]{d} & \switcher{e} \\ \switcher[f]{} & \switcher{} & \switcher[]{} & \switcher[g]{h} \end{bmatrix}$

\end{document}


The above \ifemptyarg is taken from Different command definitions with and without optional argument, while other gems also exist in Check for empty macro argument.