Generate Table via a Loop over a List

loopspdftextables

I would like to create a table that shows the evaluations of a formula for some given input list.

My initial idea was to evaluate the formula using the fp package within a \@for loop. This however does not work within a tabular environment.

My current workaround is to use tabto for formatting but that's obviously not a sustainable way when I want to add longer numbers, have nice vertical or horizontal lines, or just center the whole thing.

Minimal working example using the workaround:

\documentclass{article}

\usepackage{tabto} % just for the workaround
\usepackage{fp}

\begin{document}
\noindent
$a$ \tabto{1cm} $b$ \tabto{2cm} $a+b$\\         % table header
\makeatletter
\FPset{a}{1}
\@for \b:={1, 1.5, 2, 42}\do{
    \FPeval{\result}{round(a+b:2)}
    \a \tabto{1cm} \b \tabto{2cm} \result \\    % table row
}
\makeatother
\end{document}
  • Note that I'm not looking for a 1..N loop but one that iterates a given list of floating-point values.
  • fp is not a hard requirement, suggest an alternative if it gets in the way.
  • I would appreciate a solution working with pdflatex instead of e.g. something Lua-based.

The Question: How do I generate something like this as an actual table?

Best Answer

Perhaps by using the pgfplotstable package

 \documentclass{article}
\usepackage{pgfplotstable}
\usepackage{booktabs}
\pgfplotsset{compat=1.18}
\pgfplotstableset{
    create on use/a/.style={create col/set={1}}, % define the a column
    create on use/b/.style={create col/set list={1, 1.5, 2, 42}}, % define the b column
    create on use/tempresult/.style={
         create col/expr={(\thisrow{a}+\thisrow{b})/2}}, % result=(a+b)/2 % define the result column for the temporary table
 %
    create on use/result/.style={
        create col/copy column from table={\temptable}{tempresult}} % define the result column as a copy of the tempresult from \temptable
}

 % create two new tables \temptable and \mytable
\pgfplotstablenew[columns={a,b,tempresult}]{4}\temptable % 4 rows

\pgfplotstablenew[columns={result}]{4}\mytable

\begin{document}

\section {all columns} % 
%
% typeset the temporary table if needed
\pgfplotstabletypeset[every last row/.style={after row=\bottomrule},
    every head row/.style={before row=\toprule,after row=\midrule},
    columns/temp/.style={column name={result}}]\temptable

\section{Only the result column}
%
% typeset the final table
\pgfplotstabletypeset[every last row/.style={after row=\bottomrule},
    every head row/.style={before row=\toprule,after row=\midrule},]\mytable

\end{document}

enter image description here

Related Question