RcppEigen矩阵乘法仅返回第一个元素,重复

时间:2019-04-22 15:44:02

标签: r rcpp

RcppEigen中的简单矩阵乘法给出了正确尺寸的矩阵,但是第一个元素对所有元素重复。

Rcpp源代码,使用RcppEigen进行矩阵乘法:

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


using namespace Rcpp;

// [[Rcpp::depends(RcppEigen)]]
// [[Rcpp::export]]
NumericMatrix myfun(const NumericVector a ,  const NumericVector b) {


        const Eigen::Map<Eigen::MatrixXd> a_eig(Rcpp::as<Eigen::Map<Eigen::MatrixXd> >(a));
        const Eigen::Map<Eigen::MatrixXd> b_eig(Rcpp::as<Eigen::Map<Eigen::MatrixXd> >(b));

        return wrap(a_eig * b_eig);
}

R拨打电话:

a=matrix(data=1,nrow=10,ncol=1)
b=sample(100,10)
a * b


      [,1]
 [1,]   67
 [2,]   59
 [3,]   19
 [4,]   68
 [5,]   83
 [6,]    4
 [7,]   28
 [8,]   88
 [9,]   97
[10,]   43

myfun(a,b)

      [,1]
 [1,]   67
 [2,]   67
 [3,]   67
 [4,]   67
 [5,]   67
 [6,]   67
 [7,]   67
 [8,]   67
 [9,]   67
[10,]   67

1 个答案:

答案 0 :(得分:4)

您执行得太快了。使用中间结果-您的产品现在就是您想要的。而且,即使拥有了其余的一切,您仍然对s=df.set_index('unique_col').value.reindex(uniq).values pd.Series(s,index=uniq.index) Out[147]: 20 -0.138264 45 1.523030 47 -0.234137 51 1.579213 dtype: float64 何时有意义以及何时不有意义感到困惑。您也不需要Eigen::Mapas<>wrap()会解决这个问题。

代码

RcppEigen

输出

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

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

// [[Rcpp::export]]
Eigen::MatrixXd myfun(Eigen::Map<Eigen::MatrixXd> a,
                      Eigen::Map<Eigen::MatrixXd> b) {
  Eigen::MatrixXd res = a * b;
  return res;
}