인덱스 변수 인덱스의 수학 연산

인덱스 변수 인덱스의 수학 연산

인덱스 변수가 있는데 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 메모 이후에 제거되었습니다.

여기에 이미지 설명을 입력하세요

관련 정보