
我有一個索引變量,但我不知道如何對索引進行簡單的數學運算,例如x{\a-1}
.
我用了\tikzmath
很多;因此,我的 MWE 包括它:
\documentclass[]{standalone}
\usepackage{tikz}
\usetikzlibrary{math}
\begin{document}
\begin{tikzpicture}
\tikzmath{
\x1 = 1;
\x2 = 3;
\x3 = 5;
\x4 = 7;
%Since units are not given in \tikzmat, they will be evaluated as cm in tikz enviroment below.
}
\draw (\x{1},0) -- (10cm,10cm) node[at start, below]{\x{1}}; %This works
%\draw (\x{2-1},0) -- (10cm,10cm) node[at start, below]{\x{2-1}}; %This does not work
%\foreach \ind in {2,...,4}
%\draw (\x{\ind},0) -- (10cm,10cm) node[at start, below]{\x{\ind}}; %This works
%\foreach \ind in {2,...,4}
%\draw (\x{\ind-1},0) -- (10cm,10cm) node[at start, below]{\x{\ind-1}}; %This does not work
\end{tikzpicture}
\end{document}
答案1
該\x
巨集不會對其參數執行算術運算,但您可以讓它執行算術運算。
\documentclass{standalone}
\usepackage{tikz}
\usetikzlibrary{math}
\newcommand{\usevar}[2]{%
\expandafter#1\expandafter{\the\numexpr#2\relax}%
}
\begin{document}
\begin{tikzpicture}
\tikzmath{
\x1 = 1;
\x2 = 3;
\x3 = 5;
\x4 = 7;
%Since units are not given in \tikzmat, they will be evaluated as cm in tikz enviroment below.
}
\draw (\x{1},0) -- (10,5) node[at start, below]{\x{1}};
\draw[red] (\usevar\x{2-1},0) -- (4,5) node[at start, below]{\usevar\x{2-1}};
\foreach \ind in {2,...,4}
\draw (\x{\ind},0) -- (10,10) node[at start, below]{\x{\ind}};
\foreach \ind in {2,...,4}
\draw[red] (\usevar\x{\ind-1},0) -- (5,5) node[at start, below]{\usevar\x{\ind-1}};
\end{tikzpicture}
\end{document}
解釋
當你這樣做時\tikzmath{\x<argument>=<expression>}
,TikZ 定義了巨集\x
以及一個內部宏
\tikz@math@var@indexed@x@<argument>
進而擴展為(計算的)表達式。巨集\x
本質上是為了查看其參數並從中組成內部巨集名稱而定義的。不一定<argument>
是數學表達式,因此不會嘗試對其進行求值。
\x
因此,您需要在擴展之前執行評估(假設“下標”中只涉及整數) 。這是由 執行的任務\usevar
,它擱置\x
、擴展\the\numexpr#2\relax
、傳回一個整數,然後回到\x
(通常是它的第一個參數),現在「看到」計算出的參數。