Modular arithmetic on node names in TikZ?

半世苍凉 提交于 2019-12-02 01:47:48

问题


Say I want to construct a circulant graph in TikZ, with a variable number of nodes, labelled v0, v1, ..., v_n-1 for some n of my choice (say, 5).

I'd like to be able to use the \foreach command in TikZ to iteratively (1) define the nodes, and (2) connect the nodes. I'd like to be able to connect v_i to v_(i+1) and v_i to v_{i+2}, say.

\foreach \i in {0, ..., 4} {\path (\i*72:3) node (v\i) {};}

constructs the nodes perfectly. But then when I want to draw some lines,

\foreach \i \in {0, ..., 3} { \draw (v\i) -- (v{\i+1}); } ????

doesn't work. Nor does

\foreach \i / \j in {0/1, ..., 3/4} { \draw (v\i) -- (v{\j}); }

I get an error "no such shape v0" or something like that.

I know this must be totally easy to do, but I can't figure out how. Any suggestions?

As a followup, it would be nice to be able to connect v_i and v_{i+4} or something, with a single \foreach command, and have TikZ/pgf do the modular arithmetic for me without having to worry about spilling over.


回答1:


This worked for me:

\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{shapes,fit,arrows,positioning}
\tikzstyle{vertex} = [circle, draw, thick, text centered]
\tikzstyle{edge} = [draw, thick,->]
\begin{document}
\begin{tikzpicture}[scale=1]
  \foreach \x in {0,...,6}
    \node[vertex] (\x) at (\x*360/7:3) {v\x};
  \foreach \x/\y in {0/1,1/2,2/3,3/4,4/5,5/6,6/0}
    \draw[edge] (\x) to (\y);
\end{tikzpicture}
\end{document}

The syntax {0/1,...,5/6} did not work for me. But I admit, I spent a bit of time trying to find a good solution, and I'm still not totally satisfied.




回答2:


Another solution, achieved editing the code by Steve Tjoa:

\documentclass[tikz,border=1mm]{standalone}
\usetikzlibrary{arrows}

\begin{document}
\begin{tikzpicture}[thick]
\foreach \x in {0,...,4}{%
  \node [circle, draw] at (\x*72:3) {$v_{\x}$};
  \draw [->] (\x*72+10:3) arc (\x*72+10:\x*72+62:3);
}
\end{tikzpicture}
\end{document}



来源:https://stackoverflow.com/questions/3944802/modular-arithmetic-on-node-names-in-tikz

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!