In R, I'm trying to row-bind several identity matrices into 1 giant matrix using the code below:
> X <- 4
> Y <- 3
> block1 <- diag(X)
> for(x in 2:Y) {
> block1 <- cbind(block1,diag(X))
> }
Should look like this:
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [,11] [,12]
[1,] 1 0 0 0 1 0 0 0 1 0 0 0
[2,] 0 1 0 0 0 1 0 0 0 1 0 0
[3,] 0 0 1 0 0 0 1 0 0 0 1 0
[4,] 0 0 0 1 0 0 0 1 0 0 0 1
I feel like there is a cleaner and less memory taxing way to do this. Truth is my X is in the several thousands and Y is in the 20s so generating the matrix 'from scratch' without using these replacements in the for-loop would be preferred because I'm getting memory blockages. I tried looking at bdiag()
in the Matrix
package but that function isn't exactly what I want.
So is there a function that would do this 'from scratch'?
EDIT:
Users were kind enough to suggest I look into 'sparse Matrices.' I came across the SparseM
package and am 99% there. I simply use the as.matrix.csr
function to convert my matrices into CSR
format and together with both cbind.matrix.csr
and rbind.matrix.csr
I can efficiently get all the matrices I need. Now the issue is when I try to use it in a Linear Programming solver (Rsymphony
) I have to use as.matrix()
to convert the CSR matrix back to normal and it's still giving me a memory issue.