[Tex/LaTex] Error when using tabular environment

tables

I'm trying to create a simple table, but it just won't compile. Here's a sample bit of code:

\documentclass[11pt]{article}
\usepackage{amsmath, amssymb}
\usepackage{calc}
\usepackage{array}
\usepackage{booktabs}

\newcommand\Q{\ensuremath{\mathbb{Q}}}

\begin{document}

\begin{table}
\begin{center}
\begin{tabular}{l@{\hspace{28pt}}l@{\hspace{28pt}}p{\widthof{$\Q^2$}}@{\hspace{5pt}}p{\widthof{$\Q^2$}}@{\hspace{5pt}}p{\widthof{$\Q^2$}}@{\hspace{5pt}}p{\widthof{$\Q^2$}}@{\hspace{5pt}}p{\widthof{$\Q^2$}}@{}}
$2$ & $1$  & $0$ &     &      &     &        \\
$3$ & $3$  & $0$ & $0$ & $0$  &     &        \\
$4$ & $6$  & $0$ & $0$ & $\Q$ & $0$ & $0$    \\
$5$ & $10$ & $0$ & $0$ & $0$  & $0$ & $\Q$   \\
$6$ & $15$ & $0$ & $0$ & $0$  & $0$ & $\Q^2$ \\
$7$ & $21$ & $0$ & $0$ & $0$  & $0$ & $\Q$   \\
\end{tabular}
\end{center}
\end{table}

\end{document}

When I try to compile this, I get a sequence of errors that look like the following:

! Missing control sequence inserted.
<inserted text> 
                \inaccessible 
l.14 $2$ & $1$  & $
                   0$ &     &      &     &        \

What am I doing wrong?

Best Answer

Use a length to store the value given by \widthof; here's your code with some modifications:

\documentclass[11pt]{article}
\usepackage{amsmath, amssymb}
\usepackage{calc}
\usepackage{array}
\usepackage{booktabs}

\newcommand\Q{\mathbb{Q}}

\begin{document}

\newlength\mylen
\setlength\mylen{\widthof{$\Q^2$}}

\begin{table}
\centering
\begin{tabular}{%
  >{$}l<{$}@{\hspace{28pt}}%
  >{$}l<{$}@{\hspace{28pt}}%
  >{$}p{\mylen}<{$}@{\hspace{5pt}}%
  >{$}p{\mylen}<{$}@{\hspace{5pt}}%
  >{$}p{\mylen}<{$}@{\hspace{5pt}}%
  >{$}p{\mylen}<{$}@{\hspace{5pt}}%
  >{$}p{\mylen}<{$}@{}%
}
2 & 1  & 0 &     &      &     &        \\
3 & 3  & 0 & 0 & 0  &     &        \\
4 & 6  & 0 & 0 & \Q & 0 & 0    \\
5 & 10 & 0 & 0 & 0  & 0 & \Q   \\
6 & 15 & 0 & 0 & 0  & 0 & \Q^2 \\
7 & 21 & 0 & 0 & 0  & 0 & \Q   \\
\end{tabular}
\end{table}

\end{document}

enter image description here

  1. I used >{$}...<{$} to indicate math mode in the column format, so you don't have to explicitly use $...$ in every cell.

  2. Instead of using the center environment I used \centering to prevent adding undesired vertical space.

Related Question