2

I read this thread but I would like to have a pgfmath-function that gives the length of a list like \def\mylist{1,2,3,5,7}, because I need the value for some later calculations.

The following does not work correctly.

I get an output: 112357
It should be: 5

What do I have to do?

\documentclass[a4paper]{article}
\usepackage{tikz}

\begin{document}
\makeatletter
\pgfmathdeclarefunction{Len}{1}{%
\begingroup
\def\templist{#1}
\foreach[count=\mycount] \i in \templist {   \xdef\Len{\mycount}  }%
\Len%
\endgroup
}
\makeatother

\def\mylist{1,2,3,5,7}
\pgfmathparse{Len(\mylist)}\pgfmathresult
\end{document}

1 Answer 1

3

Note that PGF arrays should have an additional set of braces: with

\def\myarray{{1,2,3}}
\pgfmathparse{dim{\myarray}}

you get 3 stored in \pgfmathresult.

You can access the n-th item by

\pgfmathparse{\myarray[n]}

which stores in \pgfmathresult the n-th item. Remember that indexing starts at 0.

Full example:

\documentclass{article}
\usepackage{pgfmath}

\newcommand{\myarray}{{640,231,100,91,1003}}

\begin{document}

\pgfmathparse{dim{\myarray}}\pgfmathresult: should be 5

\pgfmathparse{\myarray[4]}\pgfmathresult: should be 1003

\pgfmathparse{dim({640,231,100,91,1003})}\pgfmathresult: should be 5

\pgfmathparse{dim{{640,231,100,91,1003}}}\pgfmathresult: should be 5

\end{document}

You see that dim(...) or dim{...} are equivalent, but the braces around the array are needed anyway.

enter image description here

3
  • My fault: I do ne look after sequences of the kind 1,2,...,n. The sequence could be whatever...
    – cis
    Oct 28, 2020 at 17:07
  • And I do not know, what dim calcs, e.g. \pgfmathparse{dim(200,1,3)}\pgfmathresult gives 5, but I need 3.
    – cis
    Oct 28, 2020 at 17:13
  • @cis I added a full example.
    – egreg
    Oct 28, 2020 at 18:09

You must log in to answer this question.

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