[Tex/LaTex] How to automatically calculate sums in a LaTeX table

calculationstables

Sometimes I would like LaTeX to automatically calculate sums (or other simple arithmetic) for me, eg. in a table. I would like to ensure that when I update the table, I don't accidentally forget to update some sums. I also wouldn't want to maintain the table in another program, eg. a spreadsheet, or use some external script to generate LaTeX output. Is this possible without writing a lot of macros and completely bloating the tabular syntax?

For example:

\begin{tabular}{l l l l | l}
       & Foo       & Bar       & Baz       & \\
Small  &  5        &  3        &  11       & \rowsum{} \\
Medium &  9        &  2        &  23       & \rowsum{} \\
Large  & 13        & 15        &  44       & \rowsum{} \\
\hline
       & \colsum{} & \colsum{} & \colsum{} & \\
\end{tabular}

Here, \rowsum and \colsum would somehow calculate the sum of their respective rows and columns, and I would not need to worry about calculating them by hand.

Best Answer

LaTeX is a typesetting system, and trying to use it for anything other than that will probably lead you to frustration at some point or another. Unless your table is really very simple, I think going for a spreadsheet and then exporting that to LaTeX is definitely the best way to go.

Now, having said that, for a simple table you can use, as Thorsten suggested, a package like spreadtab and write something like:

\begin{spreadtab}{{tabular}{llll|l}}
          & @ Foo      & @ Bar      & @ Baz      & \\
@ Small   & 5          & 3          & 11         & sum(b2:d2) \\
@ Medium  & 9          & 2          & 23         & sum(b3:d3) \\
@ Large   & 13         & 15         & 44         & sum(b4:d4) \\ \hline
          & sum(b2:b4) & sum(c2:c4) & sum(d2:d4) &
\end{spreadtab}

Run texdoc spreadtab on a command line to get its documentation and read the full details.