Можно ли обратиться к последнему столбцу матрицы тикз?

Можно ли обратиться к последнему столбцу матрицы тикз?

Рассмотрим следующую матрицу

введите описание изображения здесь

Эта матрица была создана с помощью кода

\begin{tikzpicture}
  \matrix[
  , matrix of nodes
  , left delimiter={[},right delimiter = {]}
  ] (m)
  {
    * & * & * & * \\
    * & * & * & * \\
    * & * & * & * \\
  };

  \node at (m-2-4) {\textbullet};

\end{tikzpicture}

Точка в позиции (1, 4) была помещена с помощью \node at (m-1-4) {\textbullet};.

Я могу захотеть добавить столбцы в эту матрицу, но я хочу, чтобы точка осталась в последнем столбце. Мне интересно, возможно ли программно ссылаться на последний столбец этой матрицы с помощью синтаксиса вроде \node at (m-1-last column index) {\textbullet};. Это возможно?

решение1

pgf имеет счетчики \pgfmatrixcurrentrowи \pgfmatrixcurrentcolumn, которые сбрасываются всякий раз, когда вы начинаете новую матрицу. Так что если вы проверите счетчики сразу после матрицы, они будут содержать количество строк и столбцов. В противном случае вы можете сохранить их в макросах. Однако в вашем примере вам нужно только

\documentclass[tikz,border=3mm]{standalone}

\usetikzlibrary{matrix}

\begin{document}
\begin{tikzpicture}
  \matrix[
  , matrix of nodes
  , left delimiter={[},right delimiter = {]}
  ] (m)
  {
    * & * & * & * \\
    * & * & * & * \\
    * & * & * & * \\
  };

  \node at (m-2-\the\pgfmatrixcurrentcolumn) {\textbullet};

\end{tikzpicture}
\end{document}

введите описание изображения здесь

Если количество столбцов меньше максимального в последней строке, то указанный выше метод не срабатывает. Вы можете определить стили для этого случая. Начиная с версии pgf 3.1.6 есть метод, который позволяет вам вынести результаты из пути. Затем вы можете извлечь их, используя соответствующий pop.

\documentclass[tikz,border=3mm]{standalone}
\usetikzlibrary{matrix}
\makeatletter
\tikzset{record number of columns in/.style={execute at end matrix={%
\edef#1{\the\pgf@matrix@numberofcolumns}%
\pgfutil@pushmacro#1}},
record number of rows in/.style={execute at end matrix={%
\edef#1{\the\pgfmatrixcurrentrow}%
\pgfutil@pushmacro#1}}
}
\newcommand\pgfpop[1]{\pgfutil@popmacro#1}
\makeatother
\begin{document}
\begin{tikzpicture}
  \matrix[matrix of nodes,
  left delimiter={[},right delimiter = {]},
  record number of columns in=\mycols,
  record number of rows in=\myrows
  ] (m)
  {
    * & * & * & * \\
    * & * & * & * \\
    * & * & * & * \\
  };
  \pgfpop\mycols
  \pgfpop\myrows
  \node[anchor=center] at (m-2-\mycols.center) {\textbullet};
\end{tikzpicture}
\end{document}

В качестве альтернативы вы можете ввести новые подсчеты.

\documentclass[tikz,border=3mm]{standalone}
\usetikzlibrary{matrix}
\newcount\tikzmatrixrows
\newcount\tikzmatrixcols
\makeatletter
\tikzset{record matrix dimensions/.style={execute at end matrix={%
\global\tikzmatrixcols=\pgf@matrix@numberofcolumns
\global\tikzmatrixrows=\pgfmatrixcurrentrow}}}
\makeatother
\begin{document}
\begin{tikzpicture}
  \matrix[matrix of nodes,
  left delimiter={[},right delimiter = {]},
  record matrix dimensions
  ] (m)
  {
    * & * & * & * \\
    * & * & * & * \\
    * & * & * & * \\
  };
  \node[anchor=center] at (m-2-\the\tikzmatrixcols.center) {\textbullet};
\end{tikzpicture}
\end{document}

Наконец, вам не обязательно знать число в точности.

\documentclass[tikz,border=3mm]{standalone}
\usetikzlibrary{matrix}
\begin{document}
\begin{tikzpicture}
  \matrix[matrix of nodes,nodes={alias=m-\the\pgfmatrixcurrentrow-last},
  left delimiter={[},right delimiter = {]}
  ] (m)
  {
    * & * & * & * \\
    * & * & * & * \\
    * & * & * & * \\
  };

  \node at (m-2-last) {\textbullet};

\end{tikzpicture}
\end{document}

решение2

Строго говоря, это не ответ на вопрос, но, возможно, некоторым будет интересно узнать, что эта функция напрямую доступна в средах nicematrix(которые создают узлы PGF/Tikz под ячейками матрицы).

\documentclass{article}
\usepackage{nicematrix}
\usepackage{tikz}

\begin{document}

$\begin{pNiceMatrix}
    * & * & * & * \\
    * & * & * & * \\
    * & * \\
\CodeAfter 
\tikz \node at (1-last) {$\bigcirc$};
\end{pNiceMatrix}$

\end{document}

Вывод кода выше

Связанный контент