[Tex/LaTex] Tikz – How to nest nodes in a matrix so they can be connected

matricesnestingtikz-pgf

I want to make a matrix which has multiple nodes in a single matrix cell. These nodes should be centered to each other. I managed to make this work by using a nested tikz environment like so:

\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{matrix}
\usetikzlibrary{positioning}
\begin{document}

\begin{tikzpicture}[auto, semithick]
    \tikzstyle{block} = [rectangle, draw, 
        minimum width=5em, text centered, rounded corners, minimum
        height=4em] 

    \matrix[matrix of nodes, row sep = 2em,
    nodes={anchor=center}
    ] (mx2){
        % First row:
        label1
        & 
        \node{\tikz{
            \node[block](n1){node1}; 
            \node[block, right=of n1](n2){node2}; 
        }};
        \\
        % Second row:
        label2
        &
        \node{\tikz{
            \node[block] (n3) 
            {node 3};
            \node[block] (n4) [right=of n3] 
            {node 4};
            \node[block] (n5) [right=of n4] 
            {node 5};
        }};
        \\
        };
    \draw (n1) -- (n4); % this fails
\end{tikzpicture}

\end{document}  

enter image description here

Now connecting these nodes is impossible because of the nested tikz environments. I have tried to get a similar image using the fit library, but I did not manage to make it work. Can any of you help me out?

Thank you in advance.

Best Answer

In general one can use the remember picture option and apply it all pictures, that should be accessible later. Since your pictures are nested and the options are inheritable, it’s sufficient to apply remember picture only to the upper level {tikzpicture}.

\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{matrix}
\usetikzlibrary{positioning}
\begin{document}

\begin{tikzpicture}[auto, semithick, remember picture,
    block/.style={rectangle, draw, 
        minimum width=5em, text centered, rounded corners,
        minimum height=4em, text width=5em}
    ]
    \matrix[matrix of nodes, row sep = 2em,
    nodes={anchor=center}
    ] (mx2){
        % First row:
        label1
        & 
        \node{\tikz{
            \node[block] (n1) {node1}; 
            \node[block, right=of n1] (n2) {node2}; 
        }};
        \\
        % Second row:
        label2
        &
        \node{\tikz{
            \node[block] (n3) {node 3};
            \node[block] (n4) [right=of n3] {node 4};
            \node[block] (n5) [right=of n4] {node 5};
        }};
        \\
    };
    \draw (n1) -- (n4); % this works
\end{tikzpicture}

\end{document} 

result

Compile twice to get the right result.

Note that I replaced \tikzstyle{block} by block/.style which is the preferred way. See Should \tikzset or \tikzstyle be used to define TikZ styles?.