
インデックス付き変数があり、 などのインデックスに対して簡単な数学演算を実行する方法がわかりません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 の注記後に削除されました。