# Place matrix into a larger matrix filled with zeros

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?

• Is it helpful mathematica.stackexchange.com/q/761/9469 ? – yarchik Mar 29 at 8:33
• indeed something like this? M = {{1, 1, 0}, {1, 0, 0}}; ArrayFlatten[{{0, M}, {0, Array[0 # &, {3, 3}]}}] – chris Mar 29 at 8:37
• You can also do A = ConstantArray[0,{5,5}]; A[[1;;2,3;;5]]+=M. This might be helpful for assembling a matrix from several overlapping submatrices. – Henrik Schumacher Mar 29 at 9:09

padLeft = Module[{dims = Dimensions @ #},
SparseArray[{Band[{1, 1 + dims[[1]]}] -> #}, {1, 1} Total @ dims]] &;



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

M = {{1, 1, 0}, {1, 0, 0}};