\sbox in math mode

I want to extract the width of an equation, but it gives me an error.

! Missing $inserted. <inserted text>$


I do not understand what is missing.

\documentclass{article}

\usepackage{mathtools}

\newcommand{\insertTableMybox}{}
\renewcommand{\insertTableMybox}{%
\begin{equation*}
W =
\begin{bmatrix}
0                 & w_{1,2} & \ldots & w_{1,U} \\
w_{2,1}           & 0       & \ldots & w_{2,U} \\
\vdots            & \vdots  & \ddots & \vdots  \\
w_{U,1} & w_{U,2} & \ldots  & 0                \\
\end{bmatrix},
\text{ where } W \in [0,1]^{U\times U}.
\end{equation*}
}

\begin{document}
\insertTableMybox
%\sbox0{\insertTableMybox} % <- not working
\fbox{\begin{minipage}{\wd0}
bla
\end{minipage}}
\end{document}


\documentclass{article}
\usepackage{mathtools,varwidth}
\newsavebox\myBox
\newcommand\insertTableMybox{%
\varwidth{\linewidth}
$W = \begin{bmatrix} 0 & w_{1,2} & \ldots & w_{1,U} \\ w_{2,1} & 0 & \ldots & w_{2,U} \\ \vdots & \vdots & \ddots & \vdots \\ w_{U,1} & w_{U,2} & \ldots & 0 \\ \end{bmatrix}, \text{ where } W \in [0,1]^{U\times U}.$
\endvarwidth
}

\begin{document}
\insertTableMybox

\fbox{\insertTableMybox}

\sbox\myBox{\insertTableMybox}  \the\wd\myBox

\end{document}

• I was actually writing the same with varwidth package. But you were faster than me. Thanks to David that pointed the use of minipage. – cacamailg Dec 5 '15 at 20:52

An \sbox is like \mbox and its content is in horizontal (LR) mode so can not have display material like an equation. You could put a minipage containing the equation in the box, but its width is then the width that you specify for the minipage.

To box a display see the \boxed command in amsmath.

• It would be useful to have the definition of \boxed. I just want to extract the width to use in another application (not shown in the MWE). – cacamailg Dec 5 '15 at 20:41
\fbox{%
\begin{minipage}{\dimexpr\wd0-2\fboxsep-2\fboxrule}
bla
\end{minipage}%
}
\end{gather*}
\end{document}