[英]Inverting a sparse matrix using eigen
我正在尝试使用稀疏求解器作为 SimplicialLLT 来求逆对称正定矩阵并返回它。
我从 R 使用 Rcpp 连接 R 和 cpp 得到一个矩阵,我将这个矩阵作为 function cpp_sparse_solver 的参数,使用 sparseView() 将其转换为 SparseMatrix,声明求解器,使用单位矩阵计算和求解系统反转它的论点。 但是,我收到错误“Eigen::MatrixXd 不是模板”。 我不是 cpp 的专家,所以我想要一些关于可能的错误的提示。
#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(Eigen::MatrixXd<double> matrix){
// START
// Declaring objects
int n = matrix.rows();
MatrixXd I = Matrix<double, n, n>::Identity();
matrix_s = matrix.sparseView();
SimplicialLLT<Eigen::SparseMatrix<double>, Lower, NaturalOrdering<int>> solver;
matrix_s.makeCompressed();
solver.compute(matrix_s);
MatrixXd Ainv = solver.solve(I);
return Ainv;
}
你的代码中有很多错误,还有一些我会做不同的风格的事情。 下面是实际编译的版本,它的不同之处在于
#include <RcppEigen.h>
// [[Rcpp::depends(RcppEigen)]]
//' Inverts matrices inside cpp
//' @param matrix Matrix to be inverted
//' @export
// [[Rcpp::export]]
Eigen::MatrixXd cpp_sparse_solver(Eigen::MatrixXd matrix){
int n = matrix.rows();
Eigen::MatrixXd I = Eigen::MatrixXd::Identity(n,n);
Eigen::SparseMatrix<double> matrix_s = matrix.sparseView();
Eigen::SimplicialLLT<Eigen::SparseMatrix<double>, Eigen::Lower,
Eigen::NaturalOrdering<int>> solver;
matrix_s.makeCompressed();
solver.compute(matrix_s);
Eigen::MatrixXd Ainv = solver.solve(I);
return Ainv;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.