Build a block diagonal matrix from a known matrix

核能气质少年 提交于 2019-12-23 10:06:47

问题


I want to build a block diagonal matrix (A) from a known matrix (B) by putting B in diagonal positions of A.

Let's say my B:

> matrix(c(1,3,4,5),nrow=2)
      [,1] [,2]
[1,]    1    4
[2,]    3    5 

I am looking for a function like this: function(B,3) (3 is just a random number) which returns matrix A like this:

[1,] 1 4 . . . .
[2,] 3 5 . . . .
[3,] . . 1 4 . .
[4,] . . 3 5 . .
[5,] . . . . 1 4
[6,] . . . . 3 5

Really appreciate any help


回答1:


We can use bdiag

library(Matrix)
bdiag(replicate(3, B, simplify = FALSE))
#6 x 6 sparse Matrix of class "dgCMatrix"

#[1,] 1 4 . . . .
#[2,] 3 5 . . . .
#[3,] . . 1 4 . .
#[4,] . . 3 5 . .
#[5,] . . . . 1 4
#[6,] . . . . 3 5

Can we wrapped in a function

fdiag <- function(mat, n) {
      bdiag(replicate(n, mat, simplify = FALSE))
}

fdiag(B, 3) 



回答2:


The desired matrix is the kronecker product of an identity matrix and B. No packages used.

B <- matrix(c(1,3,4,5),nrow=2)
diag(3) %x% B

giving:

     [,1] [,2] [,3] [,4] [,5] [,6]
[1,]    1    4    0    0    0    0
[2,]    3    5    0    0    0    0
[3,]    0    0    1    4    0    0
[4,]    0    0    3    5    0    0
[5,]    0    0    0    0    1    4
[6,]    0    0    0    0    3    5


来源:https://stackoverflow.com/questions/47955114/build-a-block-diagonal-matrix-from-a-known-matrix

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!