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}

cis
  • 8,073
  • 1
  • 16
  • 45

1 Answers1

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

egreg
  • 1,121,712