matrix manipulation diagonal

Viewed 31

I have a 3x3 matrices

 M1 <- matrix(1:9, ncol = 3)

     [,1] [,2] [,3]
[1,]    1    4    7
[2,]    2    5    8
[3,]    3    6    9

I like to create one final NxN matrix by stacking this little nxn matrices three times diagonally. All other cells are are to be filled with 0s.

  Expecting a final matrix like this.

 matrix(0:0, ncol = 9, nrow = 9)

      [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9]
 [1,]    1    4    7    0    0    0    0    0    0
 [2,]    2    5    8    0    0    0    0    0    0
 [3,]    3    6    9    0    0    0    0    0    0
 [4,]    0    0    0    1    4    7    0    0    0
 [5,]    0    0    0    2    5    8    0    0    0
 [6,]    0    0    0    3    6    9    0    0    0
 [7,]    0    0    0    0    0    0    1    4    7
 [8,]    0    0    0    0    0    0    2    5    8
 [9,]    0    0    0    0    0    0    3    6    9 

enter image description here

Not sure how to inject each matrix diagonally. Any help is appreciated. Thanks.

0 Answers
Related