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



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


 \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} {
     \draw[dagconn] ([xshift=0.2cm]x\st) to ([xshift=-0.9cm]x\en);

 \foreach \c in {1,...,3} {
   \foreach \r in {1,...,1} {
     \draw[dagconn] (x\st) to (x\en);
  • 3
    Use \pgfmathtruncatemacro – percusse Feb 20 '14 at 20:30
  • Yes, changing \pgfmathsetmacro to \pgfmathtruncatemacro fixes the problem. Thanks @percusse. – ahmadh Feb 20 '14 at 20:56

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} {
    \draw[dagconn] (x\st) to (x\en) node{\st};

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.