在@Dirk的一个非常有用的建议下,我简化了分解,这就成功了。仍然不确定为什么更复杂的结构会出错,但底线是简化就能完成任务。这是我修改后的代码-
library(Rcpp)
library(RcppEigen)
sourceCpp(code = '
#include <Rcpp.h>
#include <RcppEigen.h>
// [[Rcpp::depends(RcppEigen)]]
using namespace Rcpp;
using namespace Eigen;
using namespace RcppEigen;
// [[Rcpp::export]]
List luEigen(MatrixXd M) { // here I name our function
FullPivLU<MatrixXd> luE(M); // here I perform the decomposition
MatrixXd upper = luE.matrixLU().triangularView<Upper>(); // this creates the upper matrix
MatrixXd lower = luE.matrixLU().triangularView<StrictlyLower>(); // this creates the lower matrix
return List::create(Named("U_matrix") = upper, Named("L_matrix") = lower); // this makes the list of the 2 matrices
}')
A <- 0.8 + 0.2 * diag(100)
(luEigen(A))
您可以通过只进行一次分解并从中调用上三角矩阵和下三角矩阵来进一步加快速度,如下所示-
FullPivLU<MatrixXd> luE(M); // here I perform the decomposition
MatrixXd decomp = luE.matrixLU();
MatrixXd upper = decomp.triangularView<Upper>(); // this creates the upper matrix
MatrixXd lower = decomp.triangularView<StrictlyLower>(); // this creates the lower matrix