Longitud de una lista como función pgfmath

Oct 29 2020

Leí este hilo pero me gustaría tener una función pgfmath que proporcione la longitud de una lista como \def\mylist{1,2,3,5,7}, porque necesito el valor para algunos cálculos posteriores.

Lo siguiente no funciona correctamente.

Obtengo un resultado: 112357
debería ser:5

¿Que tengo que hacer?

\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}

Respuestas

3 egreg Oct 28 2020 at 23:57

Tenga en cuenta que las matrices PGF deben tener un conjunto adicional de llaves: con

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

obtienes 3 almacenados en \pgfmathresult.

Puede acceder al n -ésimo elemento mediante

\pgfmathparse{\myarray[n]}

que se almacena en \pgfmathresultel n -ésimo elemento. Recuerde que la indexación comienza en 0.

Ejemplo completo:

\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}

Usted ve eso dim(...)o dim{...}son equivalentes, pero las llaves alrededor de la matriz son necesarias de todos modos.