2

I want to redefine macro \\ within an instance of environment bmatrix from package amsmath. But bmatrix does not respect redefinition of \\ outside or within bmatrix:

\newcommand{\im}[1]{{
\renewcommand{\\}{;&}
\begin{bmatrix}#1\end{bmatrix}
}}
\newcommand{\im}[1]{
\begin{bmatrix}\renewcommand{\\}{;&}#1\end{bmatrix}
}
3

Instead of trying to redefine \\, I use a token cycle that pre-scans the tokens of the argument to \im, and substitutes the tokens ;& for every instance found of \\. All other tokens are echoed as they originally appear.

\documentclass{article}
\usepackage{amsmath,tokcycle}
\newcommand{\im}[1]{{\resettokcycle
  \Macrodirective{\ifx\\##1\addcytoks{;&}\else\addcytoks{##1}\fi}
  \tokencyclexpress\begin{bmatrix}#1\end{bmatrix}\endtokencyclexpress
}}
\begin{document}
$\begin{bmatrix}a\\b\end{bmatrix}$
versus
$\im{a\\b}$
\end{document}

enter image description here

3

You rather want to process your input. With expl3 it's essentially a one-liner.

\documentclass{article}
\usepackage{amsmath}

\ExplSyntaxOn

\NewDocumentCommand{\im}{m}
 {
  \begin{bmatrix}
  \seq_set_split:Nnn \l_tmpa_seq { \\ } { #1 }
  \seq_use:Nn \l_tmpa_seq { ; & }
  \end{bmatrix}
 }

\ExplSyntaxOff

\begin{document}

$\im{a\\b}$

\end{document}

enter image description here

The spacing seems a bit weird, though. You can consider not using bmatrix.

\documentclass{article}
\usepackage{amsmath}

\ExplSyntaxOn

\NewDocumentCommand{\im}{m}
 {
  \left[
  \seq_set_split:Nnn \l_tmpa_seq { \\ } { #1 }
  \seq_use:Nn \l_tmpa_seq { {;} \mspace{\thickmuskip} }
  \right]
 }

\ExplSyntaxOff

\begin{document}

$\im{a\\b}$

\end{document}

enter image description here

1
  • I’d say a two-liner.
    – Gaussler
    Jul 9 at 9:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.