When trying to make a sequence of graphs of step functions, I wrote the following code snippet:
\begin{tikzpicture} \pgfmathsetmacro{\n}{2^3}; \pgfmathsetmacro{\step}{1/\n}; \foreach \i in {0,\step,...,(\n-1)*\step} {\draw[-,thick,blue] (\i,{\i*2})--({\i+\step},{\i*2});} \end{tikzpicture} The idea is that I would like to define variables \n and \step such that all I have to do is adjust the value \n is set to, and then it will draw a step function in that many equal-sized pieces, blahblahblah. I will use this to make many different pictures within the same document.
However, it seems that defining variables in this way is not legal -- at least, I think so, since when I write this without variables it seems to work fine.
Is there a way to define variables "globally" within a tikzpicture environment?
It suddenly occurs to me ... could I just do the following?
\begin{tikzpicture} \foreach \n in {2^3} { \foreach \step in {1/n} { \foreach \i in {0,\step,...,(\n-1)*\step} {\draw[-,thick,blue] (\i,{\i*2})--({\i+\step},{\i*2});} }} \end{tikzpicture} Even if it works, it sure seems like a fragile hack ... and I would guess there is some reason why I've never seen anyone suggest doing this ... although I can't actually name a reason why it should be bad.
Is there a reason why this wouldn't work or is bad?
Update: Tested it out, doesn't quite work although doesn't utterly break, but still trying to understand why it's doing what it's doing.


(\n-1)*\stepin its own macro und use that macro in its place or useparse=trueas an option to\foreachwhich instructs it to evaluate the last element in the list for you. That said, maybe some kind ofplot, say thejump mark mid, would be more appropriate for it.parse=trueis my favorite solution! Thank you -- if you want to turn it into an answer, I'll accept it.