![在tikz foreach循环中保留坐标值](https://linux22.com/image/288019/%E5%9C%A8tikz%20foreach%E5%BE%AA%E7%8E%AF%E4%B8%AD%E4%BF%9D%E7%95%99%E5%9D%90%E6%A0%87%E5%80%BC.png)
我想保留从 tikz foreach 循环的一个步骤到下一个步骤的计算坐标值。在下面的代码中,我希望 y 值的增量取决于前一个 y 值,我将其表示为 \lasty。有没有办法保留这个值?谢谢帮助。下面的示例在包括 的情况下出现错误- \lasty
;否则示例应该可以正常工作。
\documentclass{beamer}
\usepackage{tikz}
\begin{document}
\begin{frame}[fragile]
\newcommand{\Emmett}[6]{% points, advance, rand factor, options, end label
\draw[#4] (0,0)
\foreach \x [remember=\x as \lastx] in {1,...,749}
{ -- ++(#2,{rand*#3 + #2*(#6-\lasty)/(#1-\x)})
}
node[right] {#5};
}
\scalebox{0.5}{
\begin{tikzpicture}
\draw[help lines] (0,-5) grid (15,5);
\Emmett{750}{0.02}{0.2}{red}{first one}{2.0}
\Emmett{750}{0.02}{0.2}{green}{second one}{-1.0}
\Emmett{750}{0.02}{0.2}{blue}{third one}{-2.0}
\end{tikzpicture}
}
%\pgfmathsetseed{1337}
\end{frame}
\end{document}
答案1
这是一个记住先前y
值的解决方案。
\documentclass{article}
\usepackage{tikz}
\usepackage{etoolbox}
\makeatletter
\def\ae@path{}
\newcommand{\Emmett}[6]{% points, advance, rand factor, options, end label
\def\ae@last@y{0}
\def\ae@initial@portion{\draw[#4] (0,0)}
\xdef\ae@path{\expandonce\ae@initial@portion}
\foreach \x in {1,...,749}
{
\pgfmathparse{rand*#3 + #2*(#6-\ae@last@y)/(#1-\x)}
\xdef\ae@last@y{\pgfmathresult}
\xdef\ae@path{\expandonce\ae@path -- ++(#2,\expandonce\ae@last@y)}
}
\ae@path node[right] {#5};
}
\makeatother
\begin{document}
\scalebox{0.5}{
\begin{tikzpicture}
\draw[help lines] (0,-5) grid (15,5);
\Emmett{750}{0.02}{0.2}{red}{first one}{2.0}
\Emmett{750}{0.02}{0.2}{green}{second one}{-1.0}
\Emmett{750}{0.02}{0.2}{blue}{third one}{-2.0}
\end{tikzpicture}
}
%\pgfmathsetseed{1337}
\end{document}
\typeout 用于调试
在这里,出于调试目的,您可以看到它们的 y 正在被正确更新。
\documentclass{article}
\usepackage{tikz}
\usepackage{etoolbox}
\makeatletter
\def\ae@path{}
\newcommand{\Emmett}[6]{% points, advance, rand factor, options, end label
\def\ae@last@y{0}
\def\ae@initial@portion{\draw[#4] (0,0)}
\xdef\ae@path{\expandonce\ae@initial@portion}
\foreach \x [remember=\x as \lastx (initially 0)]in {1,...,749}
{
\typeout{==>--------------------------------------------------}%%
\typeout{==>(x=\x) ==> (old y=\ae@last@y)}%%
\pgfmathparse{rand*#3 + #2*(#6-\ae@last@y)/(#1-\x)}
\xdef\ae@last@y{\pgfmathresult}
\typeout{==>(x=\x) ==> (new y=\ae@last@y)}%%
\xdef\ae@path{\expandonce\ae@path -- ++(#2,\expandonce\ae@last@y)}
}
\ae@path node[right] {#5};
}
\makeatother
\begin{document}
\scalebox{0.5}{
\begin{tikzpicture}
\draw[help lines] (0,-5) grid (15,5);
\Emmett{750}{0.02}{0.2}{red}{first one}{2.0}
\Emmett{750}{0.02}{0.2}{green}{second one}{-1.0}
\Emmett{750}{0.02}{0.2}{blue}{third one}{-2.0}
\end{tikzpicture}
}
%\pgfmathsetseed{1337}
\end{document}