Matrices and Mathtools – How to \Aboxed a Matrix in LaTeX

mathtoolsmatrices

I am trying to use \Aboxed around a function containing a pmatrix, but anything other than a column vector seems to break \Aboxed. I think it has something to do with the &'s in the matrix, but I am not sure. \boxed seems to work fine when wrapped around a matrix, but that forces me out of the align enviroment.

Here is an example of what I am trying to do, but the aboxed code is what is triggering the error if you try to compile it.

\documentclass{article}
\usepackage{color}
\usepackage{mathtools}
\usepackage{graphicx}
\usepackage{hyperref}
\usepackage{braket}
\usepackage{cancel}
\hypersetup{
colorlinks=true,
linkcolor=blue,
urlcolor=blue
}
\begin{document}
    \begin{equation}
        \boxed{ \rho^{(z)}
        =
        \begin{pmatrix}
            1   &   0   \\
            0   &   0
        \end{pmatrix}}
    \end{equation}
    \begin{align}
        \Aboxed{    \rho^{(z)}
        &=
        \begin{pmatrix}
            1   &   0   \\
            0   &   0
        \end{pmatrix}}
    \end{align}
\end{document}

Best Answer

You need to enclose the pmatrix environment in a pair of braces { }

The internal version of \Aboxed, \@Aboxed, uses & to split its argument. Normally, this just strips everything after a possible second &, as in the second example below.
In this case though, you’re splitting the pmatrix environment which would create a sequence of math-mode commands similar to the (commented) third example.

The additional { } hide these & from the \@Aboxed macro.

Code

\documentclass{article}
\usepackage{mathtools}
\begin{document}
    \begin{align}
        \Aboxed{\rho^{(z)}
        &=
        {\begin{pmatrix}
            1   &   0   \\
            0   &   0
        \end{pmatrix}}} \\
        %
        \Aboxed{\rho^z & = \rho^z & a & = b}
        %
%        \\ \rho^z & = \begin{pmatrix} 1 % <- not a good idea
    \end{align}
\end{document}

Output

enter image description here

Related Question