简体   繁体   English

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

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

矩阵

What is the fastest way to construct the matrix above in R?在 R 中构建上述矩阵的最快方法是什么? Somehow I feel there has to be a better way than the below.不知何故,我觉得必须有比下面更好的方法。

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)))

What about this?那这个呢?

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

If you want a one-liner you could do:如果你想要一个单线你可以这样做:

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

Or if you want some real code golf,或者如果你想要一些真正的代码高尔夫,

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

We could use bdiag to do this in a single line我们可以使用bdiag在一行中做到这一点

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

-output -输出

#      [,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

A matrix is just a vector with a dim attribute.矩阵只是一个带有dim属性的向量。 matrix(c(rep(c(1,-1,0,0,0),3), rep(0,17), 1, rep(c(rep(0,5), 1), 2)), ncol = 9)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM