# Tikz coordinate calculations inside foreach

As part of a drawing that will go with an explanation of diffraction, I want to draw the "outer rays" of a beam of light and draw several rays in between. An MWE of how I'm going about this is shown below:

\documentclass{standalone}
\usepackage{pgfplots,tikz}
\usetikzlibrary{calc}
\begin{document}
\begin{tikzpicture}[scale=1]
\draw[black,semithick] (-3,1) -- (0,1);
\draw[black,semithick] (-3,-1) -- (0,-1);
\def \n {10}
\foreach \s in {1,...\n-1}
{
\draw[lightgray,semithick] ($(-3,1)!\s/\n!(-3,-1)$) -- ($(0,1)!\s/\n!(0,-1)$);
}
\end{tikzpicture}
\end{document}

This gives me the following error:

Runaway argument?
\pgffor@stop \pgffor@@stop \expandafter \pgffor@dots@charcheck \pgffor@dotsvalue \ETC.
! File ended while scanning use of \pgffor@dots@stripcontext.

The pgffor@dots stuff makes me suspect the problem might lie in the range specification for \s but as far as I can tell there's nothing wrong with it. Can anyone enlighten me?

• you forgot a comma in 1,...\n-1 but that arithmetic also won't work. Use \foreach \s in {1,...,\number\numexpr\n-1} – percusse May 13 '15 at 14:15
• D'oh. Such blindness... – Wouter May 13 '15 at 14:18
• – Qrrbrbirlbel May 13 '15 at 16:23
• @Qrrbrbirlbel To be fair I don't think the questions are duplicates at all, even if the answer/underlying problem is. – Wouter May 14 '15 at 0:49

You are missing , in {1,...\n-1} which should be {1,...,\n-1} Note the , after .... Further I have defined \n-1 as a macro and taken it outside the loop (this can be done with the facilities of \foreach too though).

\documentclass{standalone}
\usepackage{pgfplots,tikz}
\usetikzlibrary{calc}
\begin{document}
\begin{tikzpicture}[scale=1]
\draw[black,semithick] (-3,1) -- (0,1);
\draw[black,semithick] (-3,-1) -- (0,-1);
\def \n {10}
\pgfmathsetmacro{\tmp}{\n-1}
\foreach \s in {1,...,\tmp}
{
\draw[lightgray,semithick] ($(-3,1)!\s/\n!(-3,-1)$) -- ($(0,1)!\s/\n!(0,-1)$);
}
\end{tikzpicture}
\end{document}

• Thanks! I should have noticed that missing , though :P However, I would like some expansion on the \n-1. I assume it doesn't work because the -1 is interpreted as a unit and not as part of an arithmetic expression. Can I do arithmetics in the range definition of a foreach loop? – Wouter May 13 '15 at 14:23
• @Wouter: percusse already told: \number\numexpr\n-1. I would go with \pgfmathsetmacro way as in my answer. – user11232 May 13 '15 at 14:24
• Ah yes, I see percusse edited their comment. Thanks again. – Wouter May 13 '15 at 14:26
• It might be appropriate to use \pgfmathtruncatemacro (it doesn't matter in this example, though). – Qrrbrbirlbel May 13 '15 at 14:38