如何在 tikz 中添加数字(用于标签)

如何在 tikz 中添加数字(用于标签)

此代码运行良好(将位标签 b0、b1、...、b7 放在框中),但现在我想在其正下方对 b8、b9、...、b15 执行相同操作。有没有办法将 8 添加到索引\k中以用于标签?

\documentclass[border=1mm]{standalone}
\usepackage{tikz}
\usetikzlibrary{arrows, calc}
\def\d{0.55cm} 
\tikzset{
  >=latex,
  mybox/.style={rectangle, very thin, draw, outer sep=0, minimum width = \d, minimum height = \d, inner sep=0}
}
\begin{document}
\begin{tikzpicture}
\foreach \k in {0,...,7} {
    \node[mybox] at (-\k*\d, 0) {$b_{\k}$};
}
\end{tikzpicture}
\end{document}

在此处输入图片描述

本质上,我想这样做:

\foreach \k in {0,...,7} {
    \node[mybox] at (-\k*\d, 0) {$b_{\k}$};
    \node[mybox] at (-\k*\d, \2*d) {$b_{somehow add 8 to \k}$};
    \node[mybox] at (-\k*\d, \4*d) {$b_{somehow add 16 to \k}$};
    \node[mybox] at (-\k*\d, \6*d) {$b_{somehow add 24 to \k}$};
}

答案1

\foreach以下是使用两个嵌套循环和evaluate获取节点文本编号的选项的建议:

\documentclass[border=1mm]{standalone}
\usepackage{tikz}
\usetikzlibrary{arrows, calc}
\def\d{0.55cm} 
\tikzset{
  >=latex,
  mybox/.style={rectangle, very thin, draw, outer sep=0pt, minimum size = \d, inner sep=0pt}
}
\begin{document}
\begin{tikzpicture}
\foreach \i in {0,...,3}{
  \foreach[evaluate={\j=int(\k+\i*8)}] \k in {0,...,7} {
    \node[mybox] at (-\k*\d, 2*\i*\d) {$b_{\j}$};
  }
}
\end{tikzpicture}
\end{document}

结果:

在此处输入图片描述

答案2

另一个解决方案为空matrixmatrix参数是总大小和行长度。

\documentclass[border=1mm]{standalone}
\usepackage{tikz}
\usetikzlibrary{matrix}
\def\d{0.55cm} 
\tikzset{
    mybox/.style={rectangle, 
        very thin, 
        draw, 
        outer sep=0pt, 
        minimum size = \d, 
        inner sep=0pt},
    mymatrix/.style 2 args={matrix of nodes,
        very thin,
        nodes in empty cells,
        nodes={mybox, anchor=center, 
            node contents = $b_{\the\numexpr#1-#2*(\pgfmatrixcurrentrow-1)-\pgfmatrixcurrentcolumn\relax}$},
        column sep=-\pgflinewidth,
        row sep = \d},
}
\begin{document}

\begin{tikzpicture}
\matrix[mymatrix={32}{8}] {
 &&&&&&&\\
 &&&&&&&\\
 &&&&&&&\\
 &&&&&&&\\};
\end{tikzpicture}
\end{document}

在此处输入图片描述

相关内容