# Variables in TikZ

I use TikZ to draw graphics in LaTeX. I'd like to do arithmetic on variables. For example I haves nodes named after N-1 and N-2 and I'd like to create the N-3 and N-4 nodes as +2 from the first nodes. Something like that:

\foreach \y in {1,2}
\node[right of=N-\y] (N-{2+\y}) {x};


is not working but is meaning what I want.

@jake

OK, that works fine. Now say I want to use it on two variables:

\foreach \x / \y in {1/2,3/4}


and I want to know \x+\y

-

I hope I understand your question:

\documentclass{book}
\usepackage{tikz}
\begin{document}
\begin{tikzpicture}
\node[circle,draw] (N-1) {N-1};
\node[rectangle,draw,below of=N-1] (N-2) {N-2};
\foreach \y in {1,2}
\pgfmathparse{int(\y+2)}
\node[right of=N-\y] (N-\pgfmathresult) {x-\pgfmathresult};

\node[right of=N-4]  {x-4 right};
\end{tikzpicture}
\end{document}

-
@Jake: Thanks. I will remove the pgfmathresult –  Marco Daniel Nov 8 '11 at 11:39

Macros in a node name are merely expanded, but not parsed by a math parser. You need to do this yourself, either by using an explicit command like Marco suggested in his answer, or by using the [evaluate = <variable> as <new macro> using <expression>] option of the \foreach statement. Note that you want to use the int(...) function to make sure the result does not have a trailing .0 (otherwise your new nodes would be called N-3.0 and N-4.0):

\documentclass{article}
\usepackage{tikz}

\begin{document}
\begin{tikzpicture}
\node (N-1) at (1,1) {N-1};
\node (N-2) at (2,-1) {N-2};
\foreach \y [evaluate = \y as \ypp using int(\y+2)] in {1,2}
\node[right of=N-\y] (N-\ypp) {N-\ypp};
\end{tikzpicture}
\end{document}


This also works if you're looping over more than one variable simultaneously:

\documentclass{article}
\usepackage{tikz}

\begin{document}
\begin{tikzpicture}
\node [text=gray] (N-1) at (1,1) {N-1};
\foreach \x/\y [evaluate = \x as \ypp using int(\y+\x)] in {1/2,3/4}
\node[right of=N-\x] (N-\ypp) {N-\ypp};
\end{tikzpicture}
\end{document}


-
OK, that works fine. Now say I want to use it on to variables: \foreach \x / \y in {1/2,3/4} and I want to know \x+\y –  Binome Nov 8 '11 at 14:56