Use foreach loop within formulas?
You're using a sledgehammer for a simple task with copy-paste. Anyway, this can't work for at least two reasons: the code of every \foreach
cycle is executed in a group and align
builds a table the same as tabular
, so each cell forms a group as well.
Even if \foreach
didn't enclose each cycle in a group, it couldn't straddle cells.
You could do
\documentclass[10pt]{article}
\usepackage{pgffor} % for foreach
\usepackage{amsmath} % for align
\usepackage{etoolbox}
\newcommand{\aligntemp}{}
\begin{document}
\gdef\aligntemp{}%
\foreach \i in {1,2,3}{%
\xappto\aligntemp{(x_\i - x_c)^2 + (y_\i - y_c)^2 &= r^2 \noexpand\\ }%
}%
\begin{align*}
\aligntemp
\end{align*}
\end{document}
Is it worth the trouble? Note that “risky” commands such as \text
should be prefixed by \noexpand
(not only \text
, of course). Also, \\
at the end would produce an undesired line.
Here's a better version:
\documentclass[10pt]{article}
\usepackage{xparse}
\usepackage{amsmath}
\ExplSyntaxOn
\NewDocumentCommand{\mathrepeat}{O{align*}mm}
{
\seq_clear:N \l_flawr_mathrepeat_seq
\clist_map_inline:nn {#2}
{
\seq_put_right:Nn \l_flawr_mathrepeat_seq { #3 }
}
\begin{#1}\seq_use:Nn \l_flawr_mathrepeat_seq { \\ }\end{#1}
}
\seq_new:N \l_flawr_mathrepeat_seq
\ExplSyntaxOff
\begin{document}
\mathrepeat{1,2,3}{
(x_{#1} - x_c)^2 + (y_{#1} - y_c)^2 &= r^2
}
\end{document}
The output is the same as before.
The optional argument to \mathrepeat
is the name of the environment to use; for instance \mathrepeat[align]{1,2,3}{...}
would number the lines.
\documentclass[10pt]{article}
\usepackage{xparse}
\usepackage{amsmath}
\ExplSyntaxOn
\NewDocumentCommand{\mathrepeat}{O{align*}mm}
{
\seq_clear:N \l_flawr_mathrepeat_seq
\clist_map_inline:nn {#2}
{
\seq_put_right:Nn \l_flawr_mathrepeat_seq { #3 }
}
\begin{#1}\seq_use:Nn \l_flawr_mathrepeat_seq { \\ }\end{#1}
}
\seq_new:N \l_flawr_mathrepeat_seq
\ExplSyntaxOff
\begin{document}
\mathrepeat[align]{1,2,3}{
(x_{#1} - x_c)^2 + (y_{#1} - y_c)^2 &= r^2 \label{myeqs#1}
}
We see in \eqref{myeqs1}--\eqref{myeqs3} that \dots
\end{document}
\documentclass[10pt]{article}
\usepackage{tikz} % for foreach
\usepackage{amsmath} % for align
\begin{document}
\foreach \i in {1,2,3}{\expandafter\xdef\csname eq\i\endcsname{%
(x_\i - x_c)^2 + (y_\i - y_c)^2 = r^2}}
\begin{align*}
\csname eq1\endcsname\\
\csname eq2\endcsname\\
\csname eq3\endcsname
\end{align*}
\end{document}