1

This question already has an answer here:

Background

I'm fairly new to tikz, and I am currently trying to create a figure with variables to easily change dimensions when needed. I am however having some troubles when attempting to apply arithmetic to my variables.

Problem

As I understand it \def\VARNAME{INITIALVALUE}, defines a variable. Using \def\a{2.4} as an example, 2*\a will evaluate as 4.8 as expected whilst 2\a will however evaluate as 22.4. I seem to hit a snag however when I attempt to multiply a variable which I have defined as a sum of two other variables.

Is what I'm trying to do not possible using the \def command or am I missing something? Is it preferred to instead use \newlength and \setlength? or perhaps \pgfmathsetmacro?


MWE:

\documentclass[tikz]{standalone}
\begin{document}
\begin{tikzpicture}

\def\thickness{5mm}  
\def\lambda{9cm}   
\def\slotW{5mm}      
\def\secW{\lambda/2-\slotW}

\draw(0,  -\thickness) rectangle +(\secW,-\thickness)    ; % as expected
\draw(0,-2*\thickness) rectangle +(2*\secW,-\thickness)  ; % this seems to evaluate to 2*\lambda/2-\slotW not 2*(\lambda/2-\slotW) as I expected
\draw(0,-3*\thickness) rectangle +(2*(\secW),-\thickness); % this won't evaluate at all

\end{tikzpicture}
\end{document}

marked as duplicate by Rmano, Community Mar 13 '17 at 10:05

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

  • 1
    Welcome to TeX - LaTeX! You should load the tikz calc library: \tikzloadlibrary{calc} and do calculations within in ($...$) constructs. – Andrew Swann Mar 13 '17 at 8:42
  • 1
    You need +({2*(\secW)},-\thickness), otherwise the closing parenthesis after \secW is seen as the closing parenthesis of the coordinate. – Torbjørn T. Mar 13 '17 at 8:56
  • Thanks @TorbjørnT. ! A concise explanation of why my code didn't work and how to solve it is exactly what I wanted. If you'd submit an answer I'd gladly accept it. – Skogsv Mar 13 '17 at 9:14
  • Don't have time right now, and this is guaranteed to be a duplicate, so if someone finds a good candidate, we may as well close I think. – Torbjørn T. Mar 13 '17 at 9:16
  • 1
    Accepted duplicate, the second suggestion is interesting as well (my original source for understanding variables), but not as concise and to the point as your first suggestion @Rmano. – Skogsv Mar 13 '17 at 10:07