0

This is, I hope, a trivial question, but one that has cost me a lot of time. I am drawing a simple TikZ picture. I define some variables which specify the coordinates of the lines, nodes and so on.

\def \Xa {4};
and then I can do
\def \Wdth {6};
\def \Xb (\Xa+\Wdth};

but the following does not work, it runs but uses the wrong value.

\def \Xmid {\Xa+\Wdth/2};

A second question is why can I not use variable names such as \X1 rather then \Xa

3
  • Please, give an MWE, read : How to make a “minimum example”
    – AndréC
    Jul 25, 2020 at 11:59
  • 1
    See the explanation by @cfr at -- tex.stackexchange.com/a/286589/197451 ---- you need to do the subcalculation first with ( ) and protect it from outside with { } -- note your first calculation shows (\Xa+\Wdth} -- something seems to be missing
    – js bibra
    Jul 25, 2020 at 12:21
  • 1
    It is a general rule of TeX that you can only use alphabets in your control word. \Xa is considered as a single control word, while \X1 is considered as a control word \X followed by a number 1. If you really want to make an exception about this you need to learn carefully of catergory codes, or to use the lengthy version of control sequences: \csname ... \endcsname.
    – domperor
    Jul 25, 2020 at 14:04

1 Answer 1

1

Without knowing more about what you are trying to do it is difficult to say but I suspect that you are going about this the wrong way. If you want an easy way to access or reuse coordinates in tikz then you should use named nodes or coordinates:

\coordinate (O) at (0,0);
\coordinate (A) at (2,3);
\draw (O)--(A);
\node (B) at (3,2){B here};
\draw(A)--(B);

If you want to set widths etc for nodes, or any tikz object, then \tikzset is your friend:

\tikzset{
  mynode/.style = {
     draw = blue,
     fill = yellow!10,
     minimum width = 20mm
  }
}

\begin{tikzpicture}
  \node[mynode] at (3,3){stuff}
\end{tikzpicture}

Importantly, you can have parameters inside \tikzset and you can also define pics, which are a very powerful way of reusing tikz code.

Finally, if you do really want to do calculations with variables like this then for integer calculations you can use:

\numexpr\Xa+\Wdth\relax

and for non-integer calculations

 \pgfmathparse{\Xa+\Wdth/2}\pgfmathresult

or, if you need to save the result in a macro,

\pgfmathsetmacro\Xmid{\Xa+\Wdth/2}

Of course, you can use \pgfmathparse for integer calculations too but if you want an honest integer then it is advisable to declare this explicitly:

\pgfmathparse{int(\Xa+\Xb)}\pgfmathresult

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .