2

How would you build a grid using a nested foreach, defining one node for each iteration?

If I were coding in Python, I would write:

nodes = {}
for i in range(10):
    for j in range(5):
         node = nodes[(i, j)] = create_node(location=(i, j), text="node text")
         if (i-1, j) in nodes:
             add_path(nodes[(i-1, j)], node, style=hstyle)
         if (i, j-1) in nodes:
             add_path(nodes[(i, j-1)], node, style=vstyle)

My code needs to be more complicated than this (it's not a simple grid), but doing this would be a great start.

  • 1
    Not sure what you mean by linking? It would be better to know exactly what you want to accomplish, and what you have attempted so far as a MWE. – Peter Grill Sep 26 '11 at 0:55
  • By linking, I mean the add_path calls, which I am using as a Python equivalent of tikz's path. – Neil G Sep 26 '11 at 1:06
5

I'm not entirely sure what the Python code does (does add_path(<node>) link the current node to the one specified in the argument?), but I gave it a shot anyway.

Here's my interpretation:

\documentclass{article}
\usepackage{tikz}

\begin{document}
\begin{tikzpicture}[
    every node/.style={draw,text width=0.5cm},
    x=1.1cm,
    y=1.1cm]
\foreach \i in {1,...,10} {
    \foreach \j [
        evaluate=\j as \jprev using int(\j-1),
        evaluate=\i as \iprev using int(\i-1)] in {1,...,5} {
        \node (\i-\j) at (\i,-\j) {\i\,\j};
        \ifnum \jprev = \i
            \draw [red, very thick] (\i-\jprev) -- (\i-\j);
        \fi
        \ifnum \iprev = \j
            \draw [red, very thick] (\iprev-\j) -- (\i-\j);
        \fi
    }
}
\end{tikzpicture}
\end{document}

  • Wow, I think this might work! I'm going to see if I can adapt this to my more complicated case and post a comment if I have any problems. Are these (\i-\j) node names? Can I say (xnode-\i-\j)? – Neil G Sep 26 '11 at 1:04
  • @NeilG: Yes, yes and simply use ({1 + 2 * \i}, {2 + 3 * \j}) for the at part in \node. – Caramdir Sep 26 '11 at 1:22
  • Thanks, I'm getting this weird error: ! Package PGF Math Error: Unknown operator e' or ev' (in 'int(1-1) evaluate') (Also, thanks Caramdir for explaining how to apply transformations to nodes. My research turned up the dollar sign notation, which is uglier, I think. I'll use yours.) – Neil G Sep 26 '11 at 1:22
  • My fault. I think I got this working. Thanks a lot!! – Neil G Sep 26 '11 at 1:31

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.