[Tex/LaTex] Matrix decomposition dimensions diagram

diagramsmatrices

What's the easiest way of making diagrams depicting matrix dimensions such as the following?

enter image description here

I can do it with simple subscripts, but I like the visual effect that these diagrams give.

Best Answer

Here I do it with stacks, setting the indices below the boxes. The primary macro is

\matbox{rows}{columns}{row index}{column index}{matrix name}.

A helper macro is \raiserows, which is like a \raisebox, except that the "length" is specified in rows, not actual length. Note that in the MWE, because X has 7 rows, while P^T only has 2 rows, P^T must be lifted (7-2)/2 = 2.5 rows.

I introduce the factor \matscale to scale your box sizes. By default, each row and column of the box size will occupy a square of size \baselineskip on a side. The factor \matscale (which defaults to 1) will scale that value.

EDITED to set array indices in \scriptstyle

\documentclass{article}
\usepackage{stackengine}
\stackMath
\newlength\matfield
\newlength\tmplength
\def\matscale{1.}
\newcommand\dimbox[3]{%
  \setlength\matfield{\matscale\baselineskip}%
  \setbox0=\hbox{\vphantom{X}\smash{#3}}%
  \setlength{\tmplength}{#1\matfield-\ht0-\dp0}%
  \fboxrule=1pt\fboxsep=-\fboxrule\relax%
  \fbox{\makebox[#2\matfield]{\addstackgap[.5\tmplength]{\box0}}}%
}
\newcommand\raiserows[2]{%
   \setlength\matfield{\matscale\baselineskip}%
   \raisebox{#1\matfield}{#2}%
}
\newcommand\matbox[5]{
  \stackunder{\dimbox{#1}{#2}{$\mathbf{#5}$}}{\scriptstyle(#3\times #4)}%
}
\parskip 1em
\begin{document}
$\renewcommand\matscale{.6}
\matbox{7}{4}{I}{J}{X} = 
\matbox{7}{2}{I}{R}{T} \raiserows{2.5}{\matbox{2}{4}{R}{J}{P^T}} +
\matbox{7}{4}{I}{J}{E}$
\end{document}

enter image description here


Just to clarify, in case it wasn't clear. One can use actual (very large) matrix dimensions, as long as one scales suitably small. For example, the following works::

$\renewcommand\matscale{.05}
\matbox{300}{75}{I}{J}{X} = 
\matbox{300}{25}{I}{R}{T} \raiserows{137.5}{\matbox{25}{75}{R}{J}{P^T}} +
\matbox{300}{75}{I}{J}{E}$