MappedSparseMatrix in RcppEigen

前端 未结 1 1433
闹比i
闹比i 2021-01-26 01:52

I want to use conjugate gradient algorithm implemented in RcppEigen package for solving large sparse matrices.

Since I am new to Rcpp and C++, I just started with the d

相关标签:
1条回答
  • 2021-01-26 02:13

    You need to use your Eigen::MappedSparseMatrix type in the Eigen::ConjugateGradient function. Try the following code:

    #include <RcppEigen.h>
    
    typedef Eigen::MappedSparseMatrix< double > mappedSparseMatrix ;
    typedef Eigen::Map< Eigen::VectorXd > mappedVector ;
    
    // [[Rcpp::depends(RcppEigen)]]
    // [[Rcpp::export]]
    Eigen::VectorXd cgSparse(
        const mappedSparseMatrix A,
        const mappedVector b
    ) {
        Eigen::ConjugateGradient< mappedSparseMatrix, Eigen::Lower > cg( A ) ;
        return cg.solve( b ) ;
    }
    

    Comparing with R's solve() function:

    B <- matrix( c( 1, 2, 0, 2, 5, 0, 0, 0, 3  ), 3, 3, TRUE )
    b <- c( 5, 1, 7 )
    B %*% solve( B, b )
           [,1]
    [1,]    5
    [2,]    1
    [3,]    7
    
    B %*% cgSparse( as( B, 'dgCMatrix' ), b )
         [,1]
    [1,]    5
    [2,]    1
    [3,]    7
    
    0 讨论(0)
提交回复
热议问题