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


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

% dim function: return dimension of an array
% dim({1,2,3}) return 3
% dim({{1,2,3},{4,5,6}}) return 2

      \advance\pgfmath@count by 1\relax


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

You can use it this way

  The dimension of $\{1,2,3\}$ is

  The dimension of $\{1,2,\{3,4\},5\}$ is

dim of an array

Related Question