在 R 中构造此稀疏矩阵的最快方法是什么

What is the fastest way to construct this sparse matrix in R

在 R 中构造上述 矩阵 的最快方法是什么?不知何故我觉得必须有比下面更好的方法。

M <- t(matrix(c(1,1,1,-1,-1,-1),nrow=3))
M <- rbind(M, matrix(rep(0,9), nrow=3))
M <- cbind(M, matrix(rep(0,5*3), ncol=3))
M <- cbind(M,rbind(matrix(rep(0,2*3),ncol=3),diag(3)))

这个呢?

M <- matrix(0,nrow = 5,ncol = 9)
M[1,1:3] <- 1
M[2,1:3] <- -1
diag(M[3:5,7:9]) <- 1

如果你想要 one-liner 你可以这样做:

t(`[<-`(`[<-`(`[<-`(matrix(0, 9, 5), 1:3, 1), 10:12, -1), 7:9, 3:5, diag(3)))
#>      [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9]
#> [1,]    1    1    1    0    0    0    0    0    0
#> [2,]   -1   -1   -1    0    0    0    0    0    0
#> [3,]    0    0    0    0    0    0    1    0    0
#> [4,]    0    0    0    0    0    0    0    1    0
#> [5,]    0    0    0    0    0    0    0    0    1

或者如果你想要一些真正的代码高尔夫,

`[<-`(`[<-`(matrix(0,5,9),c(1+0:2*5,0:2*6+33),1),2+0:2*5,-1)

矩阵只是一个具有 dim 属性的向量。 matrix(c(rep(c(1,-1,0,0,0),3), rep(0,17), 1, rep(c(rep(0,5), 1), 2)), ncol = 9)

我们可以使用 bdiag 在一行中完成此操作

library(Matrix)
as.matrix(bdiag(cbind(rbind(rep(1, 3), rep(-1, 3)), 0, 0),  diag(3)))

-输出

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