6

It seems like I'm doing something wrong when using foreach variables to indicate node numbers. The two foreach loops are anchoring the paths to the east of each node. Why does this happen?

example output

\documentclass{article}

\usepackage{tikz}
\usetikzlibrary{backgrounds,fit,patterns,decorations.pathreplacing,calc}

\makeatletter
\tikzset{
  labelnode/.style={draw=none, fill=none, black},
  latentnode/.style={draw, minimum width=5mm, shape=circle, ultra thick, black},
  dagconn/.style={arrows=->, black, thick},
}
\makeatother

\begin{document}
\begin{tikzpicture}[scale=1]
 \pgfmathsetmacro{\colgap}{1.6}
 \pgfmathsetmacro{\rowgap}{1.3}

 \node[labelnode] (x1) at (\colgap*0,\rowgap*1) {$X_1$};
 \node[labelnode] (x2) at (\colgap*1,\rowgap*1) {$X_2$};
 \node[labelnode] (x3) at (\colgap*2,\rowgap*1) {$X_3$};

 \node[latentnode,blue] (x4) at (\colgap*0,\rowgap*0) {$X_4$};
 \node[latentnode,red] (x5) at (\colgap*1,\rowgap*0) {$X_5$};
 \node[labelnode] (x6) at (\colgap*2,\rowgap*0) {$X_6$};

 \foreach \c in {1,...,2} {
   \foreach \r in {1,...,2} {
     \pgfmathsetmacro{\st}{(((\r-1)*3)+\c)}
     \pgfmathsetmacro{\en}{\st+1}
     \draw[dagconn] ([xshift=0.2cm]x\st) to ([xshift=-0.9cm]x\en);
   }
 }

 \foreach \c in {1,...,3} {
   \foreach \r in {1,...,1} {
     \pgfmathsetmacro{\st}{((\r-1)*3)+\c}
     \pgfmathsetmacro{\en}{\st+3}
     \draw[dagconn] (x\st) to (x\en);
   }
 }
\end{tikzpicture}
\end{document}
2
  • 3
    Use \pgfmathtruncatemacro
    – percusse
    Commented Feb 20, 2014 at 20:30
  • Yes, changing \pgfmathsetmacro to \pgfmathtruncatemacro fixes the problem. Thanks @percusse.
    – ahmadh
    Commented Feb 20, 2014 at 20:56

1 Answer 1

7

To not let the question unanswered, I explain why the east anchor was used and why @percusse recommended to use \pgfmathtruncatemacro.

By \pgfmathsetmacro{\st}{((\r-1)*3)+\c} you will get decimal values such as 1.0, 2.0 and 3.0. So your node names x\st will become x1.0, x2.0 and x3.0. Incidentally, those names are allowed, since that's the syntax for a so called border anchor. The expression after the dot is working as an angle given in degrees. That's why x1.0 is actually the same as x1.east. x1.90 would have been like x1.north.

So you need to get rid of the decimal point, which can be done by using \pgfmathtruncatemacro instead of \pgfmathsetmacro:

\foreach \c in {1,...,3} {
  \foreach \r in {1,...,1} {
    \pgfmathtruncatemacro{\st}{((\r-1)*3)+\c}
    \pgfmathtruncatemacro{\en}{\st+3}
    \draw[dagconn] (x\st) to (x\en) node{\st};
  }
}

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .