I want to plot some dynamical systems with tikz
but when I need to iterate on the node names, there is an error because the node name is broken when I need to work on the anchors.
I found multiple posts about accessing nodes in foreach
calls such as this one but I could not find any dealing with the anchors.
Is there a specific way to protect the node name in the loop ?
\documentclass[tikz,border = 1mm]{standalone}
\usetikzlibrary{patterns,shapes.geometric,decorations.pathmorphing}
\def\bord{0.1cm}
\def\radius{.2cm}
\tikzset{
spring/.style={thick,decorate,decoration={
zigzag,
segment length = 1mm,
amplitude=0.7mm,
pre length=1mm,
post length=1mm}},
mass/.style={circle,minimum width=2*\radius,anchor=center}
}
\begin{document}
\begin{tikzpicture}[x=1cm,y=1cm,line join=round]
% Bord gauche
\fill [pattern = north east lines] (-.3,-2) rectangle (0,.5);
\draw[thick] (0,-2) -- (0,.5);
% Right edge
\def\borddroit{8}
\fill [fill=black!30!white] (\borddroit,-2) rectangle (\borddroit+.3,.5);
\fill [pattern = north east lines] (\borddroit,-2) rectangle (\borddroit+.3,.5);
\draw[ thick] (\borddroit,-2) -- (\borddroit,.5);
% Masses
\foreach \i in {1,2,...,6}{
\node[mass,fill=blue] (m\i) at (\i,0) {};
}
\node[mass] (m0) at (0,0) {};
\node[mass,fill=red] (m7) at (7,0) {};
% Springs
% Working plot
\draw[spring] (m0.center) -- (m1.west);
% Working \foreach without anchor
\foreach \i in {0,...,6}{
\pgfmathsetmacro{\j}{\i+1}
\draw[spring] (m\i) -- (m\j) node[midway, above] (kuu\i) {$k$};
}
% Non working foreach beacause node name is broken
%\foreach \i in {0,...,6}{
% \pgfmathsetmacro{\j}{\i+1}
% \draw[spring] (m\i.east) -- (m\j.west) node[midway, above] (kuu\i) {$k^{\uu}$};
%}
\end{tikzpicture}
\end{document}
\pgfmathtruncatemacro
not\pgfmathsetmacro
, the latter makes a decimal value, so you get e.g.1.0.west
, instead of1.west
.\j
say wihtout explicitly calling\pgfmathtruncatemacro
?\foreach [evaluate={\j=int(\i+1)}] \i in {0,...,6}
or\foreach [remember=\j as \i (initially 0)] \j in {1,...,7}
.