在tikz foreach循环中保留坐标值

在tikz foreach循环中保留坐标值

我想保留从 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}

相关内容