oconnoat.com

Personal Web Site for Alexander O’Connor

Automatic Table Row Numbers in LaTeX

March10

I am writing my thesis in LaTeX at the moment, and I highly recommend it. The main advantage is the ability to mark a document up with tags, such as section and chapter numbers, which count automatically. This means that it is possible to move parts of the document around transparently, and all the references numbers will change.

I was compiling a table with numbered rows, and after moving rows a few times, decided it might be handy to be able to automatically number the rows. The code below displays the arabic numerals, but it is easy enough to choose other values.

%Declare the Counter, then initialise it.
\newcounter{rownum}
\setcounter{rownum}{0}
% Table
\begin{table}[htbp]
\caption{Table Caption}
\begin{center}
\begin{tabular}{|c||l|l|}
\hline
\textbf{\#} & \textbf{Column1} & \textbf{Column2} \\ \hline \hline
%Increment then display the counter value
\addtocounter{rownum}{1}\arabic{rownum}. & Row1Cell2 & Row1Cell3 \\ \hline
\addtocounter{rownum}{1}\arabic{rownum}. & Row2Cell2 & Row2Cell3 \\ \hline
\addtocounter{rownum}{1}\arabic{rownum}. & Row3Cell2 & Row3Cell3 \\ \hline
\end{tabular}
\end{center}
\label{tablelabel}
\end{table}%

PDF output looks like this:
table

I suspect this can be shortened using \newcommand , but I haven’t done that yet.

Some Counter Documentation.

Update: A Comment from Stefan_T corrected a typo in the script. He also mentions that the \centering command might be better than using \begin{centre}.
For those of you who are interested, here is an article on the centering vs. centre issue. My thanks go out to Stefan_T for his help!

posted under Uncategorized
  • Stefan_T
    Hi Alexander,

    there's a small typing error, instead of \begin{table}[htdp] you probably mean \begin{table}[htbp].
    By the way, I would not use \begin{center} ... \end{center} inside a table or figure environment, because it would cause additional vertical empty space, I'm preferring \centering instead, see center vs. \centering.

    Best regards,

    Stefan
blog comments powered by Disqus