20

R 是否具有将矩阵绑定为块对角线形状的基函数?

下面的工作,但我想知道是否有一个标准的方式:

a <- matrix(1:6, 2, 3)
b <- matrix(7:10, 2, 2)

rbind(cbind(a, matrix(0, nrow=nrow(a), ncol=ncol(b))),
      cbind(matrix(0, nrow=nrow(b), ncol=ncol(a)), b))

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

2 回答 2

26

adiag从一个包magic做你想要的:

library(magic)
adiag(a,b)
     [,1] [,2] [,3] [,4] [,5]
[1,]    1    3    5    0    0
[2,]    2    4    6    0    0
[3,]    0    0    0    7    9
[4,]    0    0    0    8   10

或者,您可以使用包Matrix和函数bdiag

library(Matrix)
bdiag(a,b)
4 x 5 sparse Matrix of class "dgCMatrix"

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

它返回一个稀疏矩阵,并且可能更有效。用来as.matrix(bdiag(a,b))买一个普通的。

于 2013-07-05T20:25:05.100 回答
0
foo = function(...){
    d = list(...)
    nrows = sum(sapply(d, NROW))
    ncols = sum(sapply(d, NCOL))
    ans = matrix(0, nrows, ncols)
    i1 = 1
    j1 = 1        
    for (m in d){
        i2 = i1 + NROW(m) - 1
        j2 = j1 + NCOL(m) - 1
        ans[i1:i2, j1:j2] = m
        i1 = i2 + 1
        j1 = j2 + 1
    }
    return(ans)
}

foo(a, b)
#      [,1] [,2] [,3] [,4] [,5]
# [1,]    1    3    5    0    0
# [2,]    2    4    6    0    0
# [3,]    0    0    0    7    9
# [4,]    0    0    0    8   10
于 2021-12-09T07:46:43.910 回答