4

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?

mathisfun_
  • 85
  • 4
  • 1
    Is it helpful https://mathematica.stackexchange.com/q/761/9469 ? – yarchik Mar 29 '21 at 08:33
  • 2
    indeed something like this? M = {{1, 1, 0}, {1, 0, 0}}; ArrayFlatten[{{0, M}, {0, Array[0 # &, {3, 3}]}}] – chris Mar 29 '21 at 08:37
  • 1
    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 '21 at 09:09

2 Answers2

6
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}}    *)
Roman
  • 47,322
  • 2
  • 55
  • 121
3
padLeft = Module[{dims = Dimensions @ #}, 
    SparseArray[{Band[{1, 1 + dims[[1]]}] -> #}, {1, 1} Total @ dims]] &;

padLeft @ M

enter image description here

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

kglr
  • 394,356
  • 18
  • 477
  • 896