I am drawing a surface composed of rigid "molecules" composed of three spheres each. I want to add some randomness to the surface. I have created this code:

  \foreach \i in {11,10,...,0}{
    \foreach \j in {5,4,...,0}{
      \shade[ball color=red]  (\i+\dx,{0.5*\j+\dy+0.4*sin(\i*\nuPi*10)}) circle(0.45);
      \shade[ball color=gray] (\i+\dx,{0.5*\j+\dy+0.4*sin(\i*\nuPi*10)-0.9}) circle(0.45);
      \shade[ball color=gray] (\i+\dx,{0.5*\j+\dy+0.4*sin(\i*\nuPi*10)-1.8}) circle(0.45);


judging by the resulting surface, the \dx and \dy are generated each time they are accessed and not once in each loop. Is there a way to store them?


You can store the results using \pgfmathsetmacro{<macro>}{<expression>}. Note that the the argument to functions like sin(<arg>) should be given in degrees by default. If not, you should use the "r operator". For more on parsing mathematical expressions, read section 63 Syntax for mathematical expressions (p 527 onward) in the tikz/pgf documentation.

I've modified you code snippet into an MWE and used (\xcoor,\ycoor) to represent the coordinate pair, since they were basically the same for the three shaded balls.

enter image description here

\usepackage{tikz}% http://ctan.org/pkg/pgf
  \foreach \i in {0,1,...,11}{
    \foreach \j in {5,4,...,0}{
      \pgfmathsetmacro{\xcoor}{\i+rand*0.1}% x-coordinate
      \pgfmathsetmacro{\ycoor}{0.5*\j+rand*0.1+.4*sin(\i*360/12)}% y-coordinate
      \shade[ball color=red]  (\xcoor,\ycoor) circle(0.45);
      \shade[ball color=gray] (\xcoor,\ycoor-0.9) circle(0.45);
      \shade[ball color=gray] (\xcoor,\ycoor-1.8) circle(0.45);
  • Thanks. While at it, do you know why I have to multiply the sin argument by 10 to get the wave? – Yotam Jan 9 '12 at 21:07
  • @Yotam: I've updated my answer. The argument of sin has to be an angle in degrees. If you want to specify it in radians, you need to use the r operator. – Werner Jan 9 '12 at 21:30
  • Great. Thanks. I can't re-select your answer. – Yotam Jan 10 '12 at 13:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.