# Entering block matrices for an arbitrary matrix size

Background: How to enter matrices in block matrix format? and the following:

I want to create $$f(A,t) = \left [ \begin{matrix} A & t \\ 0 & 1 \end{matrix} \right ]$$ where $A$ is a $n$ by $n$ square matrix size , and $t$ is a column vector of length $n$. The solution in the question above works for case 2, the following code works for cases 2 and 3:

  Transpose[Append[Transpose[Append[IdentityMatrix[2], {0, 0}]], {a1, a2, 1}]] // MatrixForm
Transpose[Append[Transpose[Append[IdentityMatrix[3], {0, 0, 0}]], {a1, a2, a3,1}]] // MatrixForm


Question: What is the best code for case $n$?

-

We can construct this matrix directly as a SparseArray. This allows some classes of numerical matrices to be stored as packed arrays while being combined with symbolic or exact vectors (or vice versa), so there can be storage and run-time efficiency reasons for using a SparseArray, in addition to the obvious benefit of direct construction. On the other hand, the function needed to construct a sparse block matrix is undocumented.

Define:

f[A_?MatrixQ, t_?VectorQ] /; Length[A] == Length[t] :=
SparseArraySparseBlockMatrix[{
{1, 1} -> A, {1, 2} -> Transpose[{t}], {2, 2} -> {{1}}
}, Dimensions[A] + 1];


Now:

f[IdentityMatrix[5], Array[a, 5]]


gives (as a sparse array; if you want exactly this output you must first use Normal):

-
Yes, very COOL, thank you very much. :-) –  ndroock1 Mar 27 '12 at 10:21

You could use ArrayFlatten for this, e.g.

a = Partition[Range[9], 3];
t = {"a", "b", "c"};

ArrayFlatten[{{a, Transpose[{t}]}, {0, 1}}]


Edit

A different way of constructing the matrix is by doing something like

Join[ArrayPad[a, {{0, 1}, {0, 0}}], Transpose[{Append[t, 1]}], 2]


This is effectively doing the same as you're doing already but in a more general way. The expression ArrayPad[a, {{0, 1}, {0, 0}}] will append a row of zeros to the matrix a, Transpose[{Append[t, 1]}] appends 1 to the t and turns t into a $(n+1)\times 1$ matrix, and Join[..., ..., 2] joins the two matrices. The third argument in Join indicates at which level the arrays should be joined. In this case you want to join the rows of the matrices meaning that you should join them at level 2.

-
For case 5 as well ? –  ndroock1 Mar 27 '12 at 9:17
It should work for a and t of any size, provided that the dimensions match, i.e. the length of t is the same as the number of rows in a. –  Heike Mar 27 '12 at 9:19
I just noticed that my answer is exactly the same answer as rcollyer gave in your previous question. –  Heike Mar 27 '12 at 9:23
It is my solution. The only thing I'd add is a condition to ensure that A and t were correctly sized when f` is called. –  rcollyer Mar 28 '12 at 10:58