MappedSparseMatrix in RcppEigen

て烟熏妆下的殇ゞ 提交于 2019-12-02 11:57:56

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
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!