[Tex/LaTex] Drawing a Markov chain – How to update the value of a variable in TikZ

foreachtikz-pgf

I would like to plot a simulation of a Markov process in R^2. Basically, I want to draw a line that starts at (x_0,y_0)=(0,2) and then follow this rule:
For each i=1,…,10, the line will go through (i,y_{i-1}+1) with probability 1/2 and (i,y_{i-1}-1) with probability 1/2. So I designed the following TikZ code to draw this figure:

\begin{tikzpicture}[scale=0.6]
  \coordinate[label=left:$2$] (0) at (0,2){};
  \pgfmathsetmacro{\z}{2};
  \newcounter{c};
  \setcounter{c}{0};
  \pgfmathdeclarerandomlist{dir}{{-1}{1}};

  \foreach \i in {1,2,...,10}{
    \pgfmathrandomitem{\d}{dir};
    \pgfmathsetmacro{\y}{\z+\d};
    \pgfmathsetmacro{\x}{\i};

    \coordinate (\i) at (\x,\y){};
    \pgfmathtruncatemacro{\p}{\i-1};
    \draw[red] (\p)--(\i);
    \pgfmathsetmacro{\z}{\y};
  }
  \draw[dashed,thick] (\l)--(20,2);
\end{tikzpicture}

First, we draw a coordinate at (0,2). Then, we choose \d uniformly at random from {-1,1} and draw a coordinate at (1,2+\d) and we set \z to be 2+\d. Then we choose \d again at random from {-1,1} and draw a coordinate at (2,\z+\d), and so on…

However, this does not give what the picture should look like. In fact, the updating process with \z and \y does not seem to occur, and I don't know why.

Best Answer

The problem is that TeX macro definitions are by default local and each loop iteration is inside a group. Hence the definition of \z to \y at the end of the loop is thrown away immediately afterwards and replaced by the original definition of \z as 2.

Simply replacing \pgfmathsetmacro{\z}{\y}; by \xdef\z{\y}; solves the problem (and is a lot faster too). The drawback of this is however that the new definition of \z will now globally override any macro that was stored in \z (if there happened to be one).

You could also replace the code by the following, which avoids any additional macro definitions:

\usetikzlibrary{calc}

\begin{tikzpicture}[scale=0.6]
  \coordinate[label=left:$2$] (0) at (0,2){};
  \pgfmathdeclarerandomlist{dir}{{-1}{1}};

  \foreach \i in {1,2,...,10}{
    \pgfmathrandomitem{\d}{dir};
    \pgfmathtruncatemacro{\p}{\i-1};
    \coordinate (\i) at ($(\p) + (1,\d)$) {};
    \draw[red] (\p)--(\i);
  }
\end{tikzpicture}