4

I would like to be able to have a defined macro something like this:

\def\testmacro[1]{[54.7],[74.1],[98.5]}

Such that when I call

\testmacro{2}, 

in a document,

74.1 

is printed. Is this possible?

Background:

I'm writing a C++ program that will export data to a TeX file. I have up to twenty items (but sometimes fewer), which have various measurement, like pressure. This TeX file will call for a template, which will specify how different data is actually printed. In the template, I will specify that I want to print pressure for the second item here.

I'd love to be able to say:

\def\pressure1{54.7}
\def\pressure2{74.1}

etc, but Tex can't handle numbers in macro names. Any suggestions?

Thanks, Ben

5

enter image description here

You can have numbers in command names, you just need to access them indirectly or via non-standard catcodes.

\newcount\zcount
\def\pressure{\afterassignment\zpressure\zcount}
\def\zpressure{\csname\string\pressure\the\zcount\endcsname}
\def\zdef#1#2#{\expandafter\def\csname\string#1#2\endcsname}

\zdef\pressure1{54.7}
\zdef\pressure2{74.1}
\zdef\pressure3{98.5}



Pressure 2 is \pressure2.

\bye
  • Thanks! This seems to do exactly what I want. I'm going to play with it a bit - I actually have a bunch of fields for each item (start pressure, end pressure, 02 percentage, etc) so - if I understand correctly - it looks like I'll have to duplicate lines two and three for each field. Thank you! This was extremely helpful, and it probably would have taken me a year or two - if I was lucky - to figure it out on my own. Best Regards, Ben – Ben McCandless Aug 8 '17 at 2:32
  • @BenMcCandless you can do whatever you would do if you used a,b,c instead of 1,2,3, either separate macros \pressure1{10} and \temperature1{25.6} or have one macro with two fields stuff1{{10}{25.6}} – David Carlisle Aug 8 '17 at 6:49
2

My solution based on Kpym's answer

    \documentclass[varwidth,border=7]{standalone}
    \usepackage{pgfmath}
    \begin{document}

    \def\pressureData{{1.2, 3.3, 2.3 ,3.4}}
    \def\pressure#1{\pgfmathparse{\pressureData[#1]}\pgfmathresult}

    \pressure0

    \pressure1

    \pressure2

    \pressure3      

    \end{document}

enter image description here

  • How would you add a data item the way the OP proposes (namely, \def\pressure314{3.14})? – erreka Aug 8 '17 at 0:29
  • Thank you! In my case, being able to add items after the initial declaration is a plus, but this is a great answer for situations where the entire selection of items can be defined at once. I'll definitely remember this for later. – Ben McCandless Aug 8 '17 at 2:27

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.