# How can I use \foreach in math environments?

I'm looking for a way to generate in a loop the rows of an align environment, or IEEEeqnarray or some such thing. I can see that \foreach works in math mode (inside  e.g.), but something like this

\begin{align*}
\foreach \i in {1,...,5}
{
V_\i & = 12345
}
\end{align*}


fails with

! Extra }, or forgotten \endgroup.
<template> }
\$}\ifmeasuring@ \savefieldlength@ \fi \set@field \endtemplate
l.161 \end{align*}


Can I make this work without much hassle?

The problem is that \foreach is evaluated in a group to prevent overwriting of the contents of the iteration variable. TeX does not allow alignment tabs to grouped in alignments, hence the error. You could use \pgfplotsforeachungrouped from the pgfplots package to circumvent that restriction. Also you might want to have a look at the formatting again. The output doesn't look like this is desired. You should also brace the index or you will be surprised as you hit two digit indices.

\documentclass{article}
\usepackage{mathtools,pgfplots}
\begin{document}
\begin{align*}
\pgfplotsforeachungrouped \i in {1,...,5}
{
V_{\i} & = 12345
}
\end{align*}
\end{document}


• Probably a \\ token was missing in the original. – egreg Dec 22 '15 at 10:06
• @egreg Most probably, yes, but I'll leave that as an exercise for OP. – Henri Menke Dec 22 '15 at 10:07
• Yes, the format is not intended, but I did not bother fixing it before getting it to work at all. – oarfish Dec 22 '15 at 11:15