4
$\begingroup$

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?

$\endgroup$
3
  • 1
    $\begingroup$ Is it helpful mathematica.stackexchange.com/q/761/9469 ? $\endgroup$
    – yarchik
    Commented Mar 29, 2021 at 8:33
  • 2
    $\begingroup$ indeed something like this? M = {{1, 1, 0}, {1, 0, 0}}; ArrayFlatten[{{0, M}, {0, Array[0 # &, {3, 3}]}}] $\endgroup$
    – chris
    Commented Mar 29, 2021 at 8:37
  • 1
    $\begingroup$ 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. $\endgroup$ Commented Mar 29, 2021 at 9:09

2 Answers 2

3
$\begingroup$
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)$

$\endgroup$
6
$\begingroup$
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}}    *)
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.