\ foreachのノード名を反復処理すると、\ inaccessibleエラーが発生します
Aug 20 2020
次の図に示すように、円柱状の質量を太字の水平線で接続したいと思います。

次のコードは、最初の接続で正常に機能します。
\documentclass{standalone}
\usepackage{tikz}
\usetikzlibrary{shapes,intersections}
\begin{document}
\begin{tikzpicture}
\tikzstyle{mass} = [draw, fill=gray!20, cylinder, shape aspect=1, minimum width=1.5cm, minimum height=1cm, shape border rotate=180];
\foreach \xpos/\name/\tag in {0/J1/J_1, 2/J2/J_2, 4/J3/J_3, 6/J4/\cdots, 8/J5/J_n}
{
\node[mass, name=\name] at (\xpos cm,0cm) {};
\draw[shift=(\name.center)] node[] {$\tag$};
}
\path[name path=line1] (J2.before top) -- (J2.after top);
\path[name path=line2] (J2.top) -- (J2.bottom);
\draw[name intersections={of=line1 and line2}, thick] (J1.east) -- (intersection-1);
\end{tikzpicture}
明らかな理由で、\foreach
ループを使用して接続を確立したいと思います。私は以下を試しました:
\documentclass{standalone}
\usepackage{tikz}
\usetikzlibrary{shapes,intersections}
\begin{document}
\begin{tikzpicture}
\tikzstyle{mass} = [draw, fill=gray!20, cylinder, shape aspect=1, minimum width=1.5cm, minimum height=1cm, shape border rotate=180];
\foreach \xpos/\name/\tag in {0/J1/J_1, 2/J2/J_2, 4/J3/J_3, 6/J4/\cdots, 8/J5/J_n}
{
\node[mass, name=\name] at (\xpos cm,0cm) {};
\draw[shift=(\name.center)] node[] {$\tag$};
}
\foreach \name1/\name2 in {J1/J2, J2/J3, J3/J4, J4/J5}
{
\path[name path=line1] (\name2.before top) -- (\name2.after top);
\path[name path=line2] (\name2.top) -- (\name2.bottom);
\draw[name intersections={of=line1 and line2}, thick] (\name1.east) -- (intersection-1);
}
\end{tikzpicture}
残念ながら、2番目の例では、2番目の\foreach
ループは機能しません。LaTeXは\inaccessible
コンパイル中にエラーをスローします。2番目の\foreach
ループのノード名に私が行った方法でアクセスできないようです。
回答
4 egreg Aug 20 2020 at 03:46
制御シーケンスで数字を文字と一緒に使用することはできません。
制御シーケンス名は、単一の非文字または1つ以上の文字のシーケンスのいずれかです。
だから、\name1
違法な名前は、この文脈では、一般的です。状況によってはうまくいくように見えるかもしれませんが、これを当てにしないでください。
使用する
\foreach \namea/\nameb in {J1/J2, J2/J3, J3/J4, J4/J5}
{
\path[name path=line1] (\nameb.before top) -- (\nameb.after top);
\path[name path=line2] (\nameb.top) -- (\nameb.bottom);
\draw[name intersections={of=line1 and line2}, thick] (\namea.east) -- (intersection-1);
}
パス名または座標名の番号は有効ですが、理由はまったく異なります。
4 AndréC Aug 20 2020 at 03:43
egregがコードを修正したので、他の2つは単一の変数で生成できるため、単一の変数でループを使用してコードを単純化します。

\documentclass[border=5mm,tikz]{standalone}
\usetikzlibrary{shapes,intersections}
\begin{document}
\begin{tikzpicture}
\tikzset{mass/.style={draw, fill=gray!20, cylinder, shape aspect=1, minimum width=1.5cm, minimum height=1cm, shape border rotate=180}}
\foreach \tag[count=\xpos from 0] in {J_1,J_2,J_3,\cdots,J_n}
{
\node[mass, name=J\xpos] at (2*\xpos,0) {};
\draw[shift=(J\xpos.center)] node[] {$\tag$};
}
\foreach \n [evaluate=\n as \lastn using int(\n+1)] in {0,1,2,3}
{
\path[name path=line1] (J\lastn.before top) -- (J\lastn.after top);
\path[name path=line2] (J\lastn.top) -- (J\lastn.bottom);
\draw[name intersections={of=line1 and line2}, thick] (J\n.east) -- (intersection-1);
}
\end{tikzpicture}
\end{document}