r - 你如何将类 Eigen::MatrixXd 的对象转换为类 Rcpp::NumericMatrix

标签 r eigen rcpp

我正在开发一个需要一些非常快的矩阵乘法的包,所以希望使用 RcppEigen .出于各种原因,尽管与多维数组的需要有关,但我需要将类 Eigen::MatrixXd 的创建对象转换为类 Rcpp::NumericMatrix。
我尝试反转 RcppEigen::FastLm.cpp 中列出的步骤,但这似乎不起作用
例如而不是使用const Map<MatrixXd> X(as<Map<MatrixXd> >(Xs));我试过Rcpp:NumericMatrix X(as<Rcpp::NumericMatrix>(Xs));其中 Xs 是 Eigen::MatrixXd 类的矩阵,但这似乎不起作用:”错误:没有匹配的函数用于调用 'as'
返回 Rcpp::asRcpp::NumericMatrix(z);"
如果这根本不可能,我可以尝试另一个方向。
基本上我需要在 R 语言中做的是

a = matrix(1, nrow = 10, ncol = 10)

b = array(0, c(10,10,10))

b[,,1] = a

给出一个更清晰的起始示例
我将如何将 MatrixXd 类的对象存储在 NumericMatrix 类的对象中?
#include <Rcpp.h>
#include <RcppEigen.h>
using namespace Rcpp;
using namespace Eigen;

// [[Rcpp::export]]
NumericMatrix sample_problem() {

  Eigen::MatrixXd x(2, 2); x << 1,1,2,2;

  Eigen::MatrixXd z(2, 2);

  Eigen::MatrixXd y(2,2); y << 3,3,4,4;

  z =  x * y; // do some eigen matrix multiplication

  Rcpp::NumericMatrix w(2,2);

  // what I'd like to be able to do somehow: 
  // store the results of the eigen object z in
  // a NumericMatrix w
  // w = z;

  return w;
} 

最佳答案

感谢发布代码!它使一切变得更容易。我只是重新排列了你最微小的代码。
关键的变化是通过 RcppEigen 从特征表示中“显式”返回。 helper SEXP ,然后实例化矩阵。有时......编译器需要一点点插入。
代码

#include <Rcpp.h>
#include <RcppEigen.h>

// [[Rcpp::depends(RcppEigen)]]

// [[Rcpp::export]]
Rcpp::NumericMatrix sample_problem() {

  Eigen::MatrixXd x(2, 2), y(2, 2);
  x << 1,1,2,2;
  y << 3,3,4,4;

  // do some eigen matrix multiplication
  Eigen::MatrixXd z =  x * y;

  // what I'd like to be able to do somehow:
  // store the results of the eigen object z in
  // a NumericMatrix w
  // w = z;
  SEXP s = Rcpp::wrap(z);
  Rcpp::NumericMatrix w(s);

  return w;
}

/*** R
sample_problem()
*/
演示
R> sourceCpp("demo.cpp)

R> sample_problem()
     [,1] [,2]
[1,]    7    7
[2,]   14   14
R> 
g++-9我需要-Wno-ignored-attributes或者我收到屏幕和警告屏幕......

关于r - 你如何将类 Eigen::MatrixXd 的对象转换为类 Rcpp::NumericMatrix,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62586950/

相关文章:

r - 如何对 R 中每一行的一组变体进行变异?

r - 如何使用ggplot2绘制带有类别变量的线?

r - 在亚马逊ec2上安装RcppEigen

c++ - Rcpp 没有找到 Boost header

r - 在 R 中拆分字符串并生成频率表

r - 在 R Markdown 模板中包含图像,无需为模板创建新目录

c++ - 等价于 Matlab 的 sum(A)?

c++ - 命名空间 ‘Eigen’ 中的 EigenvalueType’ 未命名类型

c++ - 在 C++ 中使用 Eigen/Sparse 库,有没有办法从稀疏矩阵中删除列?

r - 来自随机正态分布的平行样本——不是更快吗?