3

Can't seem to figure out how to create a variable containing multiple numbers.

\def\numbers{{1,2,3,4,5},{6,7,8,9,10},{11,12,13,14,15},{16,17,18,19,20},{21,22,23,24,25}}

\numbers[1][1]

Expected output

1

Actual output

1,2,3,4,5,...,[1][1]
1
  • Welcome to TeX.SE!. You define \numbers to write string of numbers 1,2,... ,25- So result is expected. ˙[1][1]˛` are not defined as part of \numbers command, so they are simple added to string. It is not clear, what you after with this command definitions
    – Zarko
    Commented Dec 6, 2022 at 16:32

1 Answer 1

7

TeX does not do magic.

WIth \def\numbers{...} you define a macro that expands to ... and

\numbers[1][1]

just prints the definition of \numbers followed by [1][1].

You can do it by programming arrays. Happily, expl3 provides the necessary infrastructure, namely clists.

We define a clist whose items are clists and it's easy to retrieve the items by row and column index.

\documentclass{article}

\ExplSyntaxOn

\NewDocumentCommand{\setarray}{mm}
 {% #1 = name, #2 = items
  \clist_clear_new:c { l_swepz_array_#1_clist }
  \clist_set:cn { l_swepz_array_#1_clist } { #2 }
 }

\NewExpandableDocumentCommand{\getarrayitem}{mmm}
 {% #1 = name, #2 = row index, #3 = column index
  \clist_item:en
   {
    \clist_item:cn { l_swepz_array_#1_clist } { #2 }
   }
   { #3 }
 }
\cs_generate_variant:Nn \clist_item:nn { e }

\ExplSyntaxOff

\begin{document}

\setarray{numbers}{
  {1,2,3,4,5},
  {6,7,8,9,10},
  {11,12,13,14,15},
  {16,17,18,19,20},
  {21,22,23,24,25}
}

\getarrayitem{numbers}{1}{1}

\getarrayitem{numbers}{4}{3}

\end{document}

enter image description here

Newlines are not necessary in \setarray, but they're better for clarity.

2
  • Thank you! How you do disable the newline?
    – Swepz
    Commented Dec 6, 2022 at 19:33
  • @Swepz You can use whatever linebreak you want, or none.
    – egreg
    Commented Dec 6, 2022 at 19:36

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .