4

I want LaTeX to automatically sum the entries in a certain table column. I know these entries will always be integers, but I can't think of a way to 'grab' their values. My first thought was something like this:

\documentclass{article}
\usepackage{array}
\begin{document}
\newcount\markcount
\markcount=0
\newcount\tmpcount
\begin{tabular}{c>{\tmpcount}c<{\advance\markcount by\tmpcount\the\tmpcount}}
a & 1 \\
b & 2 \\
\end{tabular}
\the\markcount
\end{document}

My thinking here was that the next number TeX encounters after the first \tmpcount in each row is the entry in the appropriate cell. Of course this fails due to things happening in the wrong order. Is it possible to implement something like this? I could do it by putting a command in each cell containing an integer to be summed, but there's no fun in that.

1

1 Answer 1

8

No need for the complicated answers like spreadtab if all you want to do is summing up all values in a single column. The following does that using the collcell package, a \newcolumntype and a small auxiliary macro:

\documentclass{article}

\usepackage{collcell}

\newcount\markcount
\markcount=0

\newcount\tmpcount
\newcolumntype\summingInt[2]
  {>{\collectcell{\summingIntCell{#1}}}#2<{\endcollectcell}}
\newcommand\summingIntCell[2]
  {%
    \tmpcount=\numexpr#2\relax
    \global\advance#1by\tmpcount
    \the\tmpcount
  }

\begin{document}

\begin{tabular}{c\summingInt\markcount{c}}
a & 1 \\
b & 2 \\
c & 1+2 \\
\end{tabular}
\the\markcount
\end{document}

enter image description here

1
  • I did think that spreadtab looked like overkill for my problem! Feb 23 at 17:28

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .