5

Why doesn't \posx in the following loop change? I have added manually what should be the result (second picture on the left). Any way to fix this?

\documentclass{article}

\usepackage{tikz}
\usetikzlibrary{calc}
\usepackage{pgfplots}
\usepackage{tkz-fct}
\usetkzobj{all}

\usepackage{ifthen}

\begin{document}

\newcommand{\vt}[1]{
  \pgfmathsetmacro{\posx}{0}
  \foreach \x/\y in {#1}{
    \draw[color=red,thick] (\posx,\y) -- (\x + \posx,\y);
    \pgfmathsetmacro{\posx}{\x + \posx};
  }
  \node at (5,3) {posx: \posx};
}

\begin{tikzpicture}
   \tkzInit[xmax=6,ymax=4]
   \tkzGrid
   \tkzAxeXY
   \vt{1/1,2/2,3/3}
\end{tikzpicture}
\begin{tikzpicture}
   \tkzInit[xmax=6,ymax=4]
   \tkzGrid
   \tkzAxeXY
   \draw[color=red,thick] (0,1) -- (1,1);
   \draw[color=red,thick] (1,2) -- (3,2);
   \draw[color=red,thick] (3,3) -- (6,3);
\end{tikzpicture}


\end{document}

loop.jpg

8

Affectation are local inside a \foreach loop because the whole commands are inside a group. So you need to define things globally (see the use of \xdef).

\documentclass{article}

\usepackage{tikz}
\usetikzlibrary{calc}
\usepackage{tkz-fct}
\usetkzobj{all}

\begin{document}

\newcommand{\vt}[1]{
  \pgfmathsetmacro{\posx}{0}
  \foreach \x/\y in {#1}{
    \draw[color=red,thick] (\posx,\y) -- (\x + \posx,\y);
    \pgfmathparse{\x + \posx}
    \xdef\posx{\pgfmathresult}%
  }
  \node at (5,3) {posx: \posx};
}

\begin{tikzpicture}
   \tkzInit[xmax=6,ymax=4]
   \tkzGrid
   \tkzAxeXY
   \vt{1/1,2/2,3/3}
\end{tikzpicture}
\begin{tikzpicture}
   \tkzInit[xmax=6,ymax=4]
   \tkzGrid
   \tkzAxeXY
   \draw[color=red,thick] (0,1) -- (1,1);
   \draw[color=red,thick] (1,2) -- (3,2);
   \draw[color=red,thick] (3,3) -- (6,3);
\end{tikzpicture}

\end{document}
  • exact ! Possible \global\let\posx\pgfmathresult – Alain Matthes Jan 2 '12 at 20:48

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.