3

This example is copied from this SO. but I wish to create a two dimension matrix with foreach loop\documentclass{standalone}

\usepackage{tikz}
\usetikzlibrary{matrix}
\usepackage{etoolbox}
\begin{document}
\begin{tikzpicture}
    \let\desc\empty
    \foreach \x/\y in {a/b,b/c,c/d}{%
        \xappto\desc{\expandonce{\x \\}}
        %\xappto\desc{\expandonce{\x & \y \\}}
    }
    \matrix [matrix of nodes] {
        \desc
    };
\end{tikzpicture}
\end{document}

But if I open the commented line instead the one dimension version, compile will failure!

How should I modify this example to support 2-d matrix create with foreach loop?

2 Answers 2

2

I am more or less copying this answer here. An important point is to use ampersand replacement.

\documentclass[tikz,border=3mm]{standalone}
\usetikzlibrary{matrix}
\usepackage{etoolbox}
\begin{document}
\begin{tikzpicture}
    \let\desc\empty
    \foreach \x/\y in {a/b,b/c,c/d}{%
       \xappto\desc{\x \& \y\\}%     
      }%

    \matrix [matrix of nodes,ampersand replacement=\&] {
        \desc
    };
\end{tikzpicture}
\end{document}

enter image description here

ADDENDUM: I hope this question is about using \foreach in a matrix. If you just want to have the output, you can of course do

\documentclass[tikz,border=3mm]{standalone}
\usetikzlibrary{matrix}
\begin{document}
\begin{tikzpicture}
\matrix[matrix of nodes]{a&b\\ c&d\\ e&f\\};
\end{tikzpicture}
\end{document}

which is as short as Steven's answer but has the additional possibility of adding all sorts of pgf keys to obtain something like

\documentclass[tikz,border=3mm]{standalone}
\usetikzlibrary{matrix}
\begin{document}
\begin{tikzpicture}
\matrix[matrix of math nodes,column sep=0pt,row sep=0pt,
cells={nodes={top color=blue,bottom color=red,text=white,
    minimum size=1.8em,anchor=center}}]{a&b\\ c&d\\ e&f\\};
\end{tikzpicture}
\end{document}

enter image description here

3

As long as neither the stacking TAB nor EOL is a / slash character, a simple TABstack can do this directly.

\documentclass{standalone}
\usepackage{tabstackengine}
\begin{document}
\setstackTAB{?}%
\setstackEOL{,}%
\setstacktabbedgap{1ex}%
\Matrixstack{a?b,b?c,c?d}
\end{document}

enter image description here

If you want it in text, rather than math, mode, simply change the \Matrixstack{a?b,b?c,c?d} to \tabbedCenterstack{a?b,b?c,c?d}.

enter image description here

2
  • Thanks,never know this package before! Is it possible to address elements? for example, draw a curve line from 1-2 to 3-2?
    – lucky1928
    Mar 1, 2020 at 2:51
  • @lucky1928 I'm sorry, tabstackengine is not like tikz in it graphical capabilities, so if your goal is to create a matrix and then overlay nodal "activity" upon it, it would be best to stick with tikz. Mar 1, 2020 at 3:05

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .