I have a matrix with two rows and varying column length. I want to transform this matrix into another matrix of dimensions (nrows+ncolumns)x(nrows+ncolumns) where the first two columns are filled with zeros and the first two rows of the other columns are filled with the values found in the first matrix, and the rest is again filled with zeros. Thus, assume $M=\begin{pmatrix} 1 & 1 & 0 \\ 1 & 0 & 0 \end{pmatrix}$, where nrows=2 and ncolumns=3. The result I want is thus $$\begin{pmatrix} 0 & 0 & 1 & 1 & 0 \\ 0 & 0 & 1 & 0 & 0 \\ 0 & 0 & 0 & 0 & 0 \\ 0 & 0 & 0 & 0 & 0 \\ 0 & 0 & 0 & 0 & 0 \end{pmatrix}$$ How can I achieve such a result while taking into consideration that the number of columns of the first matrix is not fixed?
2 Answers
$\begingroup$
$\endgroup$
padLeft = Module[{dims = Dimensions @ #},
SparseArray[{Band[{1, 1 + dims[[1]]}] -> #}, {1, 1} Total @ dims]] &;
padLeft @ M
TeXForm @ MatrixForm @ padLeft @ M
$\left( \begin{array}{ccccc} 0 & 0 & 1 & 1 & 0 \\ 0 & 0 & 1 & 0 & 0 \\ 0 & 0 & 0 & 0 & 0 \\ 0 & 0 & 0 & 0 & 0 \\ 0 & 0 & 0 & 0 & 0 \\ \end{array} \right)$
$\begingroup$
$\endgroup$
M = {{1, 1, 0}, {1, 0, 0}};
ArrayPad[M, {{0, Length[Transpose[M]]}, {Length[M], 0}}]
(* {{0, 0, 1, 1, 0},
{0, 0, 1, 0, 0},
{0, 0, 0, 0, 0},
{0, 0, 0, 0, 0},
{0, 0, 0, 0, 0}} *)
M = {{1, 1, 0}, {1, 0, 0}}; ArrayFlatten[{{0, M}, {0, Array[0 # &, {3, 3}]}}]
$\endgroup$A = ConstantArray[0,{5,5}]; A[[1;;2,3;;5]]+=M
. This might be helpful for assembling a matrix from several overlapping submatrices. $\endgroup$