Matrix block diagonal binding

Does R have a basis function that binds the matrix in a block diagonal shape?

The following is the work, but I want 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 from 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

Alternatively, you can use the package Matrix and the function bdiag

library(Matrix)< br />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

Returns a sparse matrix, which may be more efficient. Use as.mat rix(bdiag(a,b)) to get the regular.

Does R have a basis function that binds the matrix in a block diagonal shape?

The following is the work, but I want 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 from package magic do 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

Alternatively, you can use the package Matrix and the 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

Returns a sparse matrix, which may be more efficient. Use as.matrix(bdiag(a,b)) to get the regular one.< /p>

WordPress database error: [Table 'yf99682.wp_s6mz6tyggq_comments' doesn't exist]
SELECT SQL_CALC_FOUND_ROWS wp_s6mz6tyggq_comments.comment_ID FROM wp_s6mz6tyggq_comments WHERE ( comment_approved = '1' ) AND comment_post_ID = 5295 ORDER BY wp_s6mz6tyggq_comments.comment_date_gmt ASC, wp_s6mz6tyggq_comments.comment_ID ASC

Leave a Comment

Your email address will not be published.