[Tex/LaTex] How to find the length of a PGF array

arrayspgfmathtikz-pgf

A few of my macros currently require the user to pass the length of an array along with the array itself. It would be nice if the length could be calculated for them, as the user in question (myself) seems incapable of consistently counting beyond 3.

I've checked the pgfmanual's chapters 56 (for loops, where most of this is getting used) and 63 (mathematical functions where arrays are defined). In some sense, this is just counting commas (which I don't know how to do), but PGF has a few exceptions in arrays with () and {} allowing entries to have commas within them.

Can someone write a reasonable pgf math function that takes an array as its only argument and returns the length of that array as its result?

Best Answer

In the cvs version of pgf/tikz or in the version available for texlive at tlcontrib there is an experimental undocumented dim function in pgfmath defined as

\makeatletter
% dim function: return dimension of an array
% dim({1,2,3}) return 3
% dim({{1,2,3},{4,5,6}}) return 2
\pgfmathdeclarefunction{dim}{1}{%
  \begingroup
    \pgfmath@count=0\relax
    \expandafter\pgfmath@dim@i\pgfutil@firstofone#1\pgfmath@token@stop
    \edef\pgfmathresult{\the\pgfmath@count}%
    \pgfmath@smuggleone\pgfmathresult%
  \endgroup}

\def\pgfmath@dim@i#1{%
    \ifx\pgfmath@token@stop#1%
    \else
      \advance\pgfmath@count by 1\relax
      \expandafter\pgfmath@dim@i
    \fi}

\makeatother

This can however be very slow for large arrays (any suggestions are welcome!).

You can use it this way

\documentclass{standalone}
\usepackage{pgfmath}
\begin{document}
  The dimension of $\{1,2,3\}$ is
  \pgfmathparse{dim({1,2,3})}\pgfmathresult.

  The dimension of $\{1,2,\{3,4\},5\}$ is
  \pgfmathparse{dim({1,2,{3,4},5})}\pgfmathresult. 
\end{document}

dim of an array

Related Question