索引變數的索引中的數學運算

索引變數的索引中的數學運算

我有一個索引變量,但我不知道如何對索引進行簡單的數學運算,例如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(通常是它的第一個參數),現在「看到」計算出的參數。

答案2

對 @egreg 修復的小補充:

如果我們只想評估類似{2*\ind+5}@egreg 的表達式,解將變成:

\newcommand{\useevalof}[1]{%
  \the\numexpr#1\relax%
}

例:考慮$A_{\ind-4}$.如果\ind值為 6,$A_{\useevalof{\ind-4}}$將給出$A_2$

這對我來說真的很有用。我正在為土木工程師開發一個用於結構力學的 Tikz 庫。看看下面的圖。關卡是完全自動化的。

已註明:\expandafter在 @egreg 註解後刪除。

在此輸入影像描述

相關內容