我有一个较小的kxk矩阵m,我想从中创建多个较大的NxN对角块矩阵Q1,Q2,...,QN。确保N始终是k的倍数。
一个简单的例子应该更好地说明我的意思:
m <- matrix(c(1,3,2,4),2,2) # the small kxk matrix
m
[,1] [,2]
[1,] 1 2
[2,] 3 4
我希望得到一个6x6矩阵以下对角块矩阵:
Q1
[,1] [,2] [,3] [,4] [,5] [,6]
[1,] 1 2 0 0 0 0
[2,] 3 4 0 0 0 0
[3,] 0 0 0 0 0 0
[4,] 0 0 0 0 0 0
[5,] 0 0 0 0 0 0
[6,] 0 0 0 0 0 0
Q2
[,1] [,2] [,3] [,4] [,5] [,6]
[1,] 0 0 0 0 0 0
[2,] 0 0 0 0 0 0
[3,] 0 0 1 2 0 0
[4,] 0 0 3 4 0 0
[5,] 0 0 0 0 0 0
[6,] 0 0 0 0 0 0
Q3
[,1] [,2] [,3] [,4] [,5] [,6]
[1,] 0 0 0 0 0 0
[2,] 0 0 0 0 0 0
[3,] 0 0 0 0 0 0
[4,] 0 0 0 0 0 0
[5,] 0 0 0 0 1 2
[6,] 0 0 0 0 3 4
任何想法如何实现这一点,例如用lapply使我可以为大型矩阵做同样的事情?
答案 0 :(得分:2)
我们可以使用bdiag
Matrix
执行此操作
library(Matrix)
lst <- list(bdiag(m, diag(4)*0), bdiag(0*diag(2), m, 0*diag(2)), bdiag(diag(4)*0, m))
如果我们想将其更改为matrix
,请使用as.matrix
lapply(lst, as.matrix)
此外,这可以创建为单个sparseMatrix
bdiag(list(m, 0*diag(6))[rep(1:2, length.out=5)])