0

This question is different from \foreach inside \matrix questions 1 and 2. I was trying to do this question 3dmatrix. The \matrix command, when put inside \foreach gives the following error when multiple columns are present.

! Undefined control sequence. \pgf@matrix@last@nextcell@options l.28 } The control sequence at the end of the top line of your error message was never \def'ed. If you have...

The M(N)WE

\documentclass[tikz]{standalone}

\begin{document}
\begin{tikzpicture}

\foreach \x in {0,1,...,3}
{
    \node at(\x, 1){\x};
}

\foreach \x in {0,1,...,3}
{
\matrix [red] at(\x, 0)
{
\node {1}; \\
\node {2}; \\
\node {3}; \\
\node {4}; \\
};
}
% remove the % for the following code
%\foreach \x in {0,1,...,3}
%{
\matrix [blue] at (2,0)
{
\node {1}; & \node {2}; \\
};
%}

\end{tikzpicture}
\end{document}

Is there a workaround for this situation? (I am using texlive 2015, tikz version is tikz 2015/08/07 v3.0.1a (rcs-revision 1.151))

Also, in order to see if it is due some typo I made, I copy pasted matrix examples from pgf manual inside the foreach and it still did not work.

matrix inside foreach

Update

As per these questions, matrix path in another macro and shortcut for matrices, I am now able to put matrices in for loops by declaring macros. But now I can't access the loop variables.

\documentclass[tikz]{standalone}

\begin{document}

\begin{tikzpicture}
\useasboundingbox (-1,-1) rectangle (5, 1);

\foreach \x in {0,2,...,4}
{
\begin{scope}[xshift=\x cm]
\matrix [draw,ampersand replacement=\&]{\node {1}; \&%
\node {\x};\\
\node {3}; \&%
\node {\x};\\};
\end{scope}
}

\end{tikzpicture}
\end{document}
0

I am answering my own question so that later searches with \matrix inside \foreach will turn up a result (and it will point to the earlier helpful posts (Why is my \matrix path failing when put inside another macro? ) & (Problem with defining shortcuts for TikZ matrices. )).

\documentclass[tikz]{standalone}

\begin{document}

\begin{tikzpicture}
\useasboundingbox (-1,-1) rectangle (5, 1);

\foreach \x in {0,2,...,4}
{
\begin{scope}[xshift=\x cm]

The required option

\matrix [draw,ampersand replacement=\&]{\node {1}; \&%

rest of the code

\node {\x};\\
\node {3}; \&%
\node {\x};\\};
\end{scope}
}

\end{tikzpicture}
\end{document}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.