Search code examples
rsparse-matrix

Get eigenvalues for large dense matrix inR


I have a large matrix (36169*36169), formal class 'dgCMatrix' R package "Matrix".

I need the sum of eigenvalues, so I need to either calculate eigenvalues or the trace of this matrix.

I have tried to convert the matrix to 'normal' matrix format using as.matrix(), to be able to use matrix.trace(). Here I have memory problems, when trying to convert the file I get error message: Cholmod error 'out of memory' at file ../Core/cholmod_memory.c,

Next step I search for ways to get the diagonal values (trace) directly for the dgcMatrix, now I found that I could use

Diag signature(x = "dgCMatrix") in the Matrix package, together with setMethod, but I haven't been able to find a example on how to use it.

Does any one here have an example code showing how this work or any other solutions?


Solution

  • Try this:

    library(Matrix)
    
    set.seed(123)
    M <- as(matrix(rnorm(4), 2), "dgCMatrix") # test data
    
    sum(diag(M))
    [1] -0.4899673