5

I would like to define a variable \j in a loop \foreach \i in { 2, 4, 6} and use \j to labels of the nodes.

Here is my code:

\documentclass{standalone}
\usepackage{balance,complexity,pgfplots,tikz,tikz-3dplot}
\usetikzlibrary{calc}

\begin{document}


\begin{tikzpicture}[scale=0.4]

        \def \half {0.5};

        \foreach \i in { 2, 4, 6}
        {
            \def \j {\i*\half};
            \node[draw=none] at (\i,0) {$X_{\j}$};
            \node[draw=none] at (-\i,0) {$X'_{\j}$};
        }


\end{tikzpicture}
\end{document}

I would like to get this output:

enter image description here

Instead, I get this:

enter image description here

How can I use mathematical operators to modify the label of a node?

  • Isn't it easier doing \node[draw=none] at (2*\i,0) {$X_{\i}$}; with \foreach \i in {1,2,3}? – egreg Nov 11 '18 at 14:52
  • @egreg That is true, but I need the division or multiplication by 0.5 for a different reason. – padawan Nov 11 '18 at 14:53
  • @egreg I just realized that I could also use the method that you suggested :) – padawan Nov 11 '18 at 22:20
7

Use the \pgfmath macros (\pgfmathsetmacro for float calculations and \pgfmathtruncatemacro if you only want the integer part).

\documentclass{standalone}
\usepackage{tikz}

\begin{document}


\begin{tikzpicture}[scale=0.4]
        \pgfmathsetmacro\half {0.5};
        \foreach \i in { 2, 4, 6}
        {
            \pgfmathtruncatemacro\j{\i*\half};
            \node[draw=none] at (\i,0) {$X_{\j}$};
            \node[draw=none] at (-\i,0) {$X'_{\j}$};
        }
\end{tikzpicture}
\end{document}
7

You can do the calculations within the foreach loop with

\foreach \i [evaluate=\i as \moitie using int(\i/2)] in { 2, 4, 6} 

see page 904 of manual 3.0.1a.

half

\documentclass{standalone}
\usepackage{tikz}

\begin{document}
\begin{tikzpicture}[scale=0.4]
\foreach \i [evaluate=\i as \moitie using int(\i/2)] in { 2, 4, 6}
        {
            \node[draw=none] at (\i,0) {$X_{\moitie}$};
            \node[draw=none] at (-\i,0) {$X'_{\moitie}$};
        }
\end{tikzpicture}
\end{document}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.