矩阵的块对角线绑定 [英] Block-diagonal binding of matrices
本文介绍了矩阵的块对角线绑定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
R 是否具有以块对角线形状绑定矩阵的基函数?
Does R have a base function to bind matrices in a block-diagonal shape?
以下可以完成工作,但我想知道是否有标准方法:
The following does the job, but I'd like to know if there is a standard way:
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
推荐答案
adiag
来自一个包 magic
做你想要的:
adiag
from a package magic
does what you want:
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
Alternatively, you could use a package Matrix
and function 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))
得到一个常规的.
that returns a sparse matrix and which might be more efficient. Use as.matrix(bdiag(a,b))
to get a regular one.
这篇关于矩阵的块对角线绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文