Search code examples
rsparse-matrix

Get upper triangular non-zero elements of a sparse matrix in R


I am trying to find an efficient way to retrieve a list / vector / array of the non-zero upper triangular elements of a sparse matrix in R. For example:

    library(igraph)
    Gmini <- as.directed(graph.lattice(c(3,5)))
    GminiMat <- sparseMatrix(i=get.edgelist(Gmini)[,1],j=get.edgelist(Gmini)[,2],x=1:length(E(Gmini)))
    GminiMat

    15 x 15 sparse Matrix of class "dgCMatrix"

    [1,]  .  1  .  2  .  .  .  .  .  .  .  .  .  .  .
    [2,] 23  .  3  .  4  .  .  .  .  .  .  .  .  .  .
    [3,]  . 25  .  .  .  5  .  .  .  .  .  .  .  .  .
    [4,] 24  .  .  .  6  .  7  .  .  .  .  .  .  .  .
    [5,]  . 26  . 28  .  8  .  9  .  .  .  .  .  .  .
    [6,]  .  . 27  . 30  .  .  . 10  .  .  .  .  .  .
    [7,]  .  .  . 29  .  .  . 11  . 12  .  .  .  .  .
    [8,]  .  .  .  . 31  . 33  . 13  . 14  .  .  .  .
    [9,]  .  .  .  .  . 32  . 35  .  .  . 15  .  .  .
    [10,]  .  .  .  .  .  . 34  .  .  . 16  . 17  .  .
    [11,]  .  .  .  .  .  .  . 36  . 38  . 18  . 19  .
    [12,]  .  .  .  .  .  .  .  . 37  . 40  .  .  . 20
    [13,]  .  .  .  .  .  .  .  .  . 39  .  .  . 21  .
    [14,]  .  .  .  .  .  .  .  .  .  . 41  . 43  . 22
    [15,]  .  .  .  .  .  .  .  .  .  .  . 42  . 44  .

So ideally i would like to make a function getUpper(mat) such that getUpper(GminiMat) would yield the vector of 1:22 (the upper triangular non-zero entries of GminiMat)

Ideally, I need a fairly memory and speed efficient approach since I may need to apply it to large systems (e.g. the matrix could come from a multi-dimensional lattice with a several hundred nodes in each dimension).


Solution

  • There is a method triu in package Matrix that will return the upper triangle while preserving sparseness:

    triu(GminiMat)
    15 x 15 sparse Matrix of class "dtCMatrix"
    
     [1,] . 1 . 2 . . .  .  .  .  .  .  .  .  .
     [2,] . . 3 . 4 . .  .  .  .  .  .  .  .  .
     [3,] . . . . . 5 .  .  .  .  .  .  .  .  .
     [4,] . . . . 6 . 7  .  .  .  .  .  .  .  .
     [5,] . . . . . 8 .  9  .  .  .  .  .  .  .
     [6,] . . . . . . .  . 10  .  .  .  .  .  .
     [7,] . . . . . . . 11  . 12  .  .  .  .  .
     [8,] . . . . . . .  . 13  . 14  .  .  .  .
     [9,] . . . . . . .  .  .  .  . 15  .  .  .
    [10,] . . . . . . .  .  .  . 16  . 17  .  .
    [11,] . . . . . . .  .  .  .  . 18  . 19  .
    [12,] . . . . . . .  .  .  .  .  .  .  . 20
    [13,] . . . . . . .  .  .  .  .  .  . 21  .
    [14,] . . . . . . .  .  .  .  .  .  .  . 22
    [15,] . . . . . . .  .  .  .  .  .  .  .  .