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
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