Element-Wise Matrix Multiplication in Rcpp

前端 未结 2 1275
滥情空心
滥情空心 2020-12-11 04:47

I am working on a code that requires an element-wise matrix multiplication. I am trying to implement this in Rcpp since the code requires some expensive loops. I am fairly n

相关标签:
2条回答
  • 2020-12-11 05:07

    If you want to fake it, you can follow what's done here and use Rcpp's sugar on regular vectors, and convert them to matrices as needed:

    #include <Rcpp.h>
    using namespace Rcpp;
    
    // [[Rcpp::export]]
    NumericVector multMat(NumericMatrix m1, NumericMatrix m2) {
      NumericVector multMatrix = m1 * m2;
      multMatrix.attr("dim") = Dimension(m1.nrow(), m1.ncol());
      return multMatrix;
    }
    
    /*** R
    multMat( matrix(1:9, nrow=3), matrix(1:9, nrow=3) )
    */
    

    But, as Dirk said, you're better off using RcppArmadillo for matrix operations.

    0 讨论(0)
  • 2020-12-11 05:23

    You probably want to use RcppArmadillo (or RcppEigen) for actual math on matrices.

    R> library(RcppArmadillo)
    R> cppFunction("arma::mat schur(arma::mat& a, arma::mat& b) { 
    +                   return(a % b); }", depends="RcppArmadillo")
    R> schur(matrix(1:4,2,2), matrix(4:1,2,2))
         [,1] [,2]
    [1,]    4    6
    [2,]    6    4
    R> 
    

    Element-wise multiplication is also called Schur (or Hadamard) multiplication. In Armadillo, the % supports it; see the Armadillo docs for more.

    0 讨论(0)
提交回复
热议问题