使用Eigen的SimplicialLLT求稀疏矩阵逆时遇编译错误求助
错误排查:Eigen::MatrixXd is not a template 问题解决
你的代码存在三个关键语法/用法错误,直接导致了编译报错,以下是逐一修复方案:
错误点与修复方法
MatrixXd模板参数误用
Eigen中的MatrixXd是预定义的动态大小double类型矩阵,等价于Matrix<double, Dynamic, Dynamic>,不需要额外添加<double>模板参数。函数参数里的Eigen::MatrixXd<double>属于语法错误,直接改为Eigen::MatrixXd即可(或因已声明using namespace Eigen;,直接写MatrixXd)。未声明
matrix_s变量
代码中直接赋值matrix_s = matrix.sparseView();,但未提前声明该变量的类型。需要在使用前明确声明:SparseMatrix<double> matrix_s = matrix.sparseView();动态大小单位矩阵创建错误
Matrix<double, n, n>::Identity()中的n是运行时变量,而Matrix<double, n, n>是编译期固定大小的矩阵类型,无法适配运行时维度。应该改用动态矩阵类MatrixXd的静态方法创建单位矩阵:MatrixXd I = MatrixXd::Identity(n, n);
修正后的完整代码
#include <cmath> #include <Rcpp.h> #include <RcppEigen.h> #include <stdio.h> #include <R.h> #include <Rmath.h> #include <Eigen/Dense> #include <Eigen/Sparse> #include <Eigen/OrderingMethods> #include <Eigen/SparseCholesky> using namespace Eigen; using namespace Rcpp; using namespace std; // [[Rcpp::depends(RcppEigen)]] //' Inverts matrices inside cpp //' @param matrix Matrix to be inverted //' @export // [[Rcpp::export]] MatrixXd cpp_sparse_solver(MatrixXd matrix){ // START // Declaring objects int n = matrix.rows(); MatrixXd I = MatrixXd::Identity(n, n); SparseMatrix<double> matrix_s = matrix.sparseView(); SimplicialLLT<SparseMatrix<double>, Lower, NaturalOrdering<int>> solver; matrix_s.makeCompressed(); solver.compute(matrix_s); MatrixXd Ainv = solver.solve(I); return Ainv; }
内容的提问来源于stack exchange,提问作者sergio.azevedo
相关产品推荐
相关产品推荐

