5

I have a function that have parameters that need to calculate large numbers at some point in that function, I want to use pgfmath to cumulate the data (since counters don't have enough range):

...
\pgfkeys{/pgf/fpu=true}
\pgfmathsetmacro\csname Total#1\endcsname{\csname Total#1\endcsname + #2} %does not work probably missing a \expandafter
\pgfmathsetmacro\TotalContractH{\TotalContractH + #2}
\pgfmathsetmacro\temp{#2 * #3}
\pgfmathsetmacro\TotalContractC{\TotalContractC + \temp}
\pgfkeys{/pgf/fpu=false}
...

How can I acheive the dynamic name for that thing. Thanks in advance

5

In \pgfsetmacro\csname Total#1\endcsname{...}, the first argument of \pgfsetmacro is \csname and not the dynamic macro. Therefore, \csname needs to be expanded first:

\expandafter\pgfsetmacro\csname Total#1\endcsname{...}
3

Add, in the preamble,

\newcommand\pgfmathsetmacroname[1]{%
  \expandafter\pgfmathsetmacro\csname#1\endcsname
}

Then something like

\pgfmathsetmacroname{Total#1}{\csname Total#1\endcsname + #2}

ought to work.

A more complete example:

\documentclass{article}

\usepackage{tikz}

\newcommand\pgfmathsetmacroname[1]{%
  \expandafter\pgfmathsetmacro\csname#1\endcsname
}

\newcommand\settotal[2]{%
  \pgfmathsetmacroname{Total#1}{#2}%
}
\newcommand{\usetotal}[1]{\csname Total#1\endcsname}

\begin{document}

\settotal{A}{1}% starting value
\settotal{A}{\usetotal{A}+2}
\settotal{A}{\usetotal{A}*3}

\usetotal{A}

\end{document}

This prints, as expected,

9.0

2

\csname <stuff>\endcsname needs to be expanded before resulting in \<stuff>; easily achievable via a couple of \expandafters. Also, create macros to make your life a little easier:

10
30.0

\documentclass{article}

\usepackage{tikz}

\newcommand{\newContract}[2]{%
  \expandafter\pgfmathsetmacro\csname Total#1\endcsname{#2}%
}
\newcommand{\addtoContract}[2]{%
  \def\contractAssign{\expandafter\pgfmathsetmacro\csname Total#1\endcsname}%
  \expandafter\contractAssign\expandafter{\csname Total#1\endcsname + #2}%
}

\newcommand{\contractValue}[1]{\csname Total#1\endcsname}

\begin{document}

\newContract{ABC}{10}\contractValue{ABC}

\addtoContract{ABC}{20}\contractValue{ABC}

\end{document}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.