Paw in Data
Paw in Data

Reputation: 1604

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

matrix

What is the fastest way to construct the matrix above in 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)))

Upvotes: 1

Views: 67

Answers (4)

akrun
akrun

Reputation: 887901

We could use bdiag to do this in a single line

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

Upvotes: 0

Allan Cameron
Allan Cameron

Reputation: 174526

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)

Upvotes: 2

bcarlsen
bcarlsen

Reputation: 1441

A matrix is just a vector with a dim attribute. matrix(c(rep(c(1,-1,0,0,0),3), rep(0,17), 1, rep(c(rep(0,5), 1), 2)), ncol = 9)

Upvotes: 0

ThomasIsCoding
ThomasIsCoding

Reputation: 102710

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

Upvotes: 4

Related Questions