8

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$?

nilo de roock
  • 9,657
  • 3
  • 35
  • 77

2 Answers2

14

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] := 
 SparseArray`SparseBlockMatrix[{
  {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):

matrix resulting from the given input

Oleksandr R.
  • 23,023
  • 4
  • 87
  • 125
7

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.

Heike
  • 35,858
  • 3
  • 108
  • 157