The LaTeX Atrocities — Domimatrix
I'm currently having a lot of fun doing my quantum computing course. I'm going to blame this work on this, but it was actually because someone asked me if I knew how to do it, and when I'm in a doing things mood I find it impossible put something like this down.
The task was a more concise way to write matrices when typing in LaTeX -
most people use array
or align
, and have to deal
with the column definitions, tab separators, and different kinds of line
breaking characters
My solution was ultimately a lot simpler - you start your matrix, stating how many columns it should have. Then, you give all the cell values, separated by commas. I feel that this is a more intuitive way of specifying the contents, and it still allows you to lay them out in the source code as you feel best.
The following code represents the first simple test case - a two by two matrix, with the cells labelled with the letters a-d
\domimatrix{2}{a,b,c,d}
The equivalent code using an array environment is
\begin{array}{cc} a & b \\ c & d \end{array}
Already, there is a small code space advantage to this method, which you can see will increase as the matrix gets larger. There are also no real limitations to this method, as commas can still be included in the values be wrapping them in their own group with braces. In addition, line breaks and other whitespace characters are handled like the whitespace elsewhere in latex - ignored pretty much entirely! Consider this Quantum Phi gate, with the values being given as radial pairs.
\domimatrix{2}{
{\langle 1, 0 \rangle}, {\langle 0, 0 \rangle},
{\langle 0, 0 \rangle}, {\langle 1, \phi \rangle}
}
(For those who don't use them, \langle and \rangle are the left and right angle brackets, which are often incorrectly substituted with the less than and greater than signs < and >)
How does it work?
This was, once I had it figured out, quite easy to code; it is essentially a macro for the array syntax that I mentioned earlier. The full source code can be found in my LaTeX-Things library, which also includes various tools and templates for use.
There are three main commands - \domimatrix
, which sets up the layout
by ensuring we're in maths mode, putting in left and right parentheses, and -
of course - the array environment. This column specification is created by
\dmmakecolumn
, which uses a horrible large amount
of code to write the letter "c" n times.
All that is left is writing out the values, which is made very simple by the
\csvloop
command. This calls
\dmmakecell
for each cell, which works out the
appropriate separator, and outputs the value.