# Mathematical calculation within \foreach loop in tikz

The minimal code below demonstrates the problem. The code as it is does not give the desired output. I assume the \x-\y is not being correctly handled. I have tried including braces, brackets, but to no avail.

\documentclass{article}

\usepackage{tikz}
\usetikzlibrary{calc}

\newcommand{\connection}[4][]{\draw[{#1}] (#2#3)--([yshift={#4cm}]#2#3) --([yshift={#4cm}]#2#3-|#3#2)--(#2#3-|#3#2)}

\begin{document}

\begin{tikzpicture}

% create the coordinates
\foreach \Lletter/\l in {A/0,B/1,C/2}
{\foreach \Rletter/\r in {A/0,B/1,C/2}
{\coordinate (\Lletter\Rletter) at ({\l+\r/10},0);}
}

% create the paths
\foreach \L/\x in {A/5}
{\foreach \R/\y in {A/0,B/1,C/2}
{\connection{\L}{\R}{\x-\y};}
}

% this is the desired result
% \connection{A}{A}{5};
% \connection{A}{B}{4};
% \connection{A}{C}{3};

\end{tikzpicture}

\end{document}

• try \foreach \L/\x in {A/5} {\foreach \R/\y in {A/0,B/1,C/2} {\pgfmathsetmacro\result{\x-\y} \connection{\L}{\R}{\result};} } – touhami May 8 '16 at 17:56
• Just in case you do know it: "an empty line, in the body, is a paragraph break" -thus you want to avoid empty lines for markup. tex.stackexchange.com/questions/272926/… – hpekristiansen May 8 '16 at 22:55
• @Hans-PeterE.Kristiansen In a tikzpicture spaces and empty lines usually don't matter (exception before the environment's optional argument, see Q41567). A nullfont is installed. – Qrrbrbirlbel May 9 '16 at 12:13
• The problem is indeed the subtraction, as #4 gets replaced by \x-\y and thus: \x-\y cm becomes \x pt - \y cm. Use either (#4)*1cm or, staying in the local coordinate system: shift=(up:{#4}). – Qrrbrbirlbel May 9 '16 at 12:18

As touhami said, one way is to include an explicit call to \pgfmathsetmacro within the loop. However, since this is a loop, we might as well use the facilities provided by \foreach itself to evaluate variables using pgfmath expressions.

For example

\documentclass[tikz,border=10pt,multi]{standalone}
\newcommand{\connection}[4][]{%
\draw [{#1}] (#2#3) -- ([yshift={#4cm}]#2#3) -- ([yshift={#4cm}]#2#3 -| #3#2) -- (#2#3 -| #3#2)
}
\begin{document}
\begin{tikzpicture}
\foreach \Lletter/\l in {A/0,B/1,C/2}
{\foreach \Rletter/\r in {A/0,B/1,C/2}
{\coordinate (\Lletter\Rletter) at ({\l+\r/10},0);}
}
\foreach \L/\x in {A/5}
{\foreach \R/\y [evaluate=\y as \z using {\x-\y}] in {A/0,B/1,C/2}
{\connection{\L}{\R}{\z};}
}
\end{tikzpicture}
\end{document}


• Might also be a good idea to introduce OP to count=\l from 0. – Qrrbrbirlbel May 9 '16 at 12:20
• @Qrrbrbirlbel I assumed those were just examples, to be honest. Perhaps you're right, though. – cfr May 9 '16 at 22:03