Nicematrix: handle with empty cells / drawing lines into a NiceArray

arraysmatricesnicematrix

enter image description here

I would like to add/draw lines (like the shown red one) over and under the letters A, B and D (not at the \cdots) – each to the upper and lower end of the matrix.

What is nicematrix's correct method for that?

· There seems to be a problem at drawing at "empty cells". Does nicematrix know a key like TikZ-matrix's nodes into empty cells ?

· Can I do that task elegantly with a foreach-loop?

\documentclass{article}
\usepackage{amsmath}

\usepackage{nicematrix} 
\usepackage{tikz} 
\begin{document}
$\begin{NiceArray}{(c c c c) }
    &     &           &      \\
A  & B  & \cdots  & D     \\
    &     &           &      \\
\CodeAfter
\begin{tikzpicture}[]
%\draw[red] (2-1) -- (1-1); % does not work-->' No shape named `1-1' is known.'
\draw[red] (2-1) -- (1.5|-1); % work
\end{tikzpicture}
\end{NiceArray}$
\end{document}

Best Answer

Your Tikz instruction \draw (2-1) -- (1-|1.5) ; seems good (if I actually understand what you want to draw...).

For a loop, it's possible (for example) to use a foreach loop (provided by pgffor which is loaded by pgf, itself loaded by nicematrix).

Here is an example:

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

\begin{document}

$\begin{NiceArray}{(c c c c)}
  \NotEmpty  &     &           &      \\
A  & B  & \cdots  & D     \\
    &     &           &      \\
\CodeAfter
  \begin{tikzpicture} [red]
   \foreach \i in {1,...,\value{jCol}} 
      { 
        \draw (2-\i) -- (1-|\i.5) ; 
        \draw (2-\i) -- (last-|\i.5) ; 
      } ; 
  \end{tikzpicture}
\end{NiceArray}$

\end{document}

In the \CodeAfter the LaTeX counter jCol contains the total number of columns of the array (whereas in the body of the array, it contains the number of the current column).

Output of the above code

You say in your question that you don't want any rule above and below the \cdots. Of course, the previous code does not automatically detect the command \cdots in the cell... Do you actually want a code with an automatic detection of the position of the potential commands \cdots (it's possible to write a code with such feature, but it's not straightforward)?