# Matrix color blocks

I am looking to produce a matrix multiplication where one of the matrices consists of coloured blocks. Much like:

Is there any way to produce something like this in Latex?

-

I did this with stacks. Unfortunately, there is some tailoring that one must do, depending on the arrangement of boxes, so each particular image must be thought through. The \colblock[color]{rows}{content} is the basic unit. \belowbaseline[length]{} is used in \colblock to align boxes at their top. That and \belowbaseline[length]{} can be used in the code to shift/align boxes. Passing either of them a multiple of \baselineskip would allow some staggering in the vertical box placement.

If the \colblocks are allowed to be rectangular (I assumed square), let me know so that I may correct the answer.

\documentclass{article}
\usepackage{stackengine}
\usepackage{xcolor}
\usepackage{calc}
\newlength\mytemp
\newlength\myoffset
\myoffset=.5\ht\strutbox
\newcommand\colblock[3][blue!20]{%
\setlength\mytemp{#2\baselineskip}%
\setlength\mytemp{.5\mytemp-\myoffset}%
\belowbaseline[0pt]{%
\fboxsep=-\fboxrule\fbox{\colorbox{#1}{\rule[-\mytemp]{0ex}{#2\baselineskip}%
\makebox[#2\baselineskip]{$#3$}}}%
}}
\begin{document}
\parenVectorstack{b_1 b_2 . . . . . b_n} = \left( \raisebox{4\baselineskip+.5\myoffset}{% \def\stackalignment{l}\stackunder[0pt]{\colblock{2}{-2}\colblock{2}{-2}}% {\colblock{6}{-1}\colblock[red!15]{4}{1}}% }% \right) \parenVectorstack{a_1 a_2 . . . . . a_n}
\end{document}


-

A solution that uses tikz, but hides it in markup:

\begin{blockmatrix}
\block[blue](0,0)text(2,2)
\end{blockmatrix}


Draws a block with color blue at position (0,0) with size (2,2) and "text" in the middle. Thus different colors and rectangles are supported.

\documentclass{article}
\usepackage{amsmath}
\usepackage{xcolor}
\usepackage{tikz}
\usetikzlibrary{calc}

\definecolor{block}{RGB}{0,162,232}

\newenvironment{blockmatrix}{%
\left(%
\vcenter\bgroup\hbox\bgroup
\tikzpicture[
x=1.5\baselineskip,
y=1.5\baselineskip,
]%
}{%
\endtikzpicture
\egroup
\egroup
\right)%
}

% \block[#1](#2,#3)#4(#5,#6)
% #1:      fill color
% (#2,#3): lower left corner
% #4:      text in the middle
% (#5,#6): size of the block
\newcommand*{\block}[1][block]{%
\blockaux{#1}%
}
\def\blockaux#1(#2,#3)#4(#5,#6){%
\draw[fill={#1}]
let \p1=(#2,#3),
\p2=(#5,#6),
\p3=(#2+#5,#3+#6),
\p4=(#2+#5/2,#3+#6/2)
in
(\p1) rectangle (\p3)
(\p4) node {$#4$}
;%
}

\begin{document}
$\begin{pmatrix}b_1\\b_2\\\vdots\\b_n\end{pmatrix} = \begin{blockmatrix} \block(0,0)-1(3,3) \block(3,1)1(2,2) \block[yellow](0,3)-2(1,1) \block[green](1,3)2(1,1) \end{blockmatrix} \begin{pmatrix}a_1\\a2\\\vdots\\a_n\end{pmatrix}$
\end{document}


-