Search code examples
rsparse-matrix

Block sparse matrices as sparse matrices


Given a sparse matrix M, which is 32x24 I'm trying to create a larger sparse matrix of this form:

A = [[O(32),M],[t(M),O(24)]]

Here O(n) is a zero sparse matrix of dimension nxn.

M itself is a block matrix:

M = [[m.aa,m.ab],[m.ba,m.bb]]

where m.ij is 16x12.

I'm using the Matrix package for sparsematrix and blockmatrix for blockmatrix. One problem I have is that the use.as.blockmatrix=FALSE parameter, which works nicely for ordinary block matrices, seems not to work properly for block sparse matrices. I can't take the transpose of the block matrices in question, which makes the construction of A difficult.

Here's how I'm generating m.ij:

  m.aa<-rsparsematrix(
    #dimensions:
    nrow=16,ncol=12,
    nnz=20,
    rand.x=function(x) 1 )

  m.ab<-rsparsematrix(
    #dimensions:
    nrow=16,ncol=12,
    nnz=10,
    rand.x=function(x) 1 )

 m.ba<-rsparsematrix(
    nrow=16,ncol=12,
    nnz=0,
    rand.x=function(x) 1 )

  m.bb<-m.aa



M<-blockmatrix(dim=c(2,2),names=c("maa","mba","mab","mbb"),
                 maa=m.aa,mab=m.ab,mba=m.ba,mbb=m.bb,
                 use.as.blockmatrix=FALSE)

But attr(M,"class") shows M is still a blockmatrix, even though I have use.as.blockmatrix=FALSE.

I can create O(32) and O(24), but t(M) gives me the error message argument is not a matrix, so I can't use it for block A(2,1) :(

A might be constructed with something like:

Mt<-t(M)

O32<-rsparsematrix(nrow=32,ncol=32,nnz=0)
O24<-rsparsematrix(nrow=24,ncol=24,nnz=0)

A<-blockmatrix(dim=c(2,2),names=c("RR","BR","RB","BB"), RR=O32,RB=M,BR=Mt,BB=O24)

Solution

  • This is perhaps a little awkward, but rather than using blockmatrix you can put together the appropriate blocks yourself using rBind(), cBind(), and Matrix(0,...):

    M <- cBind(rBind(m.aa,m.ba),rBind(m.ab,m.bb))   
    A <- rBind(
        cBind(Matrix(0,32,32), M              ),
        cBind(t(M),            Matrix(0,24,24))
    )