8

I'm trying to create a table using the foreach loops made available in the pgffor package. Using the following code, I am able to generate the right contents, but not aligned properly.

\begin{tabular}{c}
    \foreach \i in {0,...,7}{
        \foreach \j in {0,...,7}{
            (\i,\j)
        }
    }
\end{tabular}

However, as soon as I try to add line endings (see below), ..

\begin{tabular}{c}
    \foreach \i in {0,...,7}{
        \foreach \j in {0,...,7}{
            (\i,\j) \\
        }
    }
\end{tabular}

I get the following error:

! Missing \endgroup inserted.
<inserted text> 
                \endgroup 
l.237         }

I don't see what I'm doing wrong. Can anyone point it out to me?

2

1 Answer 1

3

Add the contents of the table to a macro before you typeset it:

\documentclass{article}

\usepackage{pgffor,etoolbox}

\newcommand*\mytablecontents{}
\foreach \i in {0,...,7}{
  \foreach \j in {0,...,7}{
    \xappto\mytablecontents{(\i,\j) }
  }
  \gappto\mytablecontents{\\}
}

\begin{document}

\begin{tabular}{c}
  \mytablecontents
\end{tabular}

\end{document}

enter image description here

The code above uses etoolbox's \appto<macro>{<stuff>} which adds <stuff> to the macro <macro>. Or rather it uses its brothers \gappto which adds <stuff> globally (this is important because \foreach performs its loop inside a group) and \xappto which adds <stuff> globally and also expands <stuff> before its added to <macro>. The latter is important because otherwise (\i,\j) would be added multiple times but outside the loop \i and \j have another meaning – you'd get lots of “(ı,ȷ)”.

4
  • How can I arrange `\foreach \i in {1,...,6}{ \foreach \j in {1,...,6} \foreach \k in {1,...,6} { \xappto\mytablecontents{(\i,\j,) } Commented Jan 18, 2017 at 22:30
  • @toandhsp I don't understand your question. If you replace {0,...,7} with {1,...,6} both times you'll get (1,1) in the uper left corner and (6,6) in the lower right but I guess that's not the question, no?
    – cgnieder
    Commented Jan 18, 2017 at 22:33
  • @clements My question is \foreach \i in {1,...,6}{ \foreach \j in {1,...,6} \foreach \k in {1,...,6} { \xappto\mytablecontents{(\i,\j,\k) } } Commented Jan 18, 2017 at 22:41
  • @toandhsp first you have to decide how you want to arrange the triplets and then you can ask a question of how to achieve the arrangement with LaTeX. Otherwise I'm not sure I can be of any help…
    – cgnieder
    Commented Jan 18, 2017 at 22:55

You must log in to answer this question.

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