Draw a hierarchical matrix pattern

matricespatterntikz-pgf

How to draw a hierarchical matrix pattern like this one (using TikZ or not)?
And how to add a little square matrix between the product between the two retangular matrices?

Is it possible to create a building block that could be reused in the next levels of the hierarchical structure without repeating the same code?

enter image description here

I think the building block could be something like that:

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

\begin{document}
  \begin{tikzpicture}[baseline={(0, 1.75cm)}]
    \draw (0,0) rectangle (4,4);
    \filldraw [ fill={gray} ] (0,2) rectangle (2,4);
    \filldraw [ fill={gray} ] (2,0) rectangle (4,2);
    
    \filldraw [ fill={gray} ] (0.1,1) rectangle (0.4,1.8);
    \filldraw [ fill={gray} ] (0.5,1.5) rectangle (0.8,1.8);
    \filldraw [ fill={gray} ] (0.9,1.5) rectangle (1.7,1.8);
    
    \filldraw [ fill={gray} ] (2.1,3) rectangle (2.4,3.8);
    \filldraw [ fill={gray} ] (2.5,3.5) rectangle (2.8,3.8);
    \filldraw [ fill={gray} ] (2.9,3.5) rectangle (3.7,3.8);
  \end{tikzpicture}}
\end{document]

Best Answer

Description

  • defined pics for the two rectangles (rectangles) and for the square (x0)
  • further pics xi are defined recursively with \defxi
  • the scale is used as a parameter for the recursion

Code

\documentclass[border=3mm]{standalone}

\usepackage{tikz}

\tikzset{
    x0/.pic={
        \draw[fill={gray}] (0,0) rectangle (1,1);
    },
    rectangles/.pic={
        \draw[fill={gray}] (0.1,0.8) rectangle (.3,.2);
        \draw[fill={gray}] (0.4,0.8) rectangle (.9,.6);
    },
    every pic/.style={transform shape},
}

\newcommand{\defxi}[1]{
    \tikzset{
        x#1/.pic={
            \draw[scale=##1] (0,0) rectangle (1,1);
            \pic[scale=.5*##1] at (0,.5) {x\the\numexpr#1-1\relax=##1};
            \pic[scale=.5*##1] at (.5,0) {x\the\numexpr#1-1\relax=##1};
            \pic[scale=.5*##1] at (0,0) {rectangles};
            \pic[scale=.5*##1] at (.5,.5) {rectangles};
        }
    }
}

\defxi{1}
\defxi{2}
\defxi{3}
\defxi{4}

\begin{document}
\begin{tikzpicture}
    \foreach \i in {0, ..., 4} {
        \pic at (\i*1.2,0) {x\i=1};
    }
\end{tikzpicture}
\end{document}

Result

enter image description here