Question

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 new to Rcpp, and may be missing something, but I cannot get the element-wise matrix multiplication to work.

// [[Rcpp::export]]

NumericMatrix multMat(NumericMatrix m1, NumericMatrix m2) {
    NumericMatrix multMatrix = m1 * m2 // How can this be implemented ?
}

I may be missing something very trivial, and wanted to ask if there was any method to do this (other than using loops to iterate over each element and multiply).

Thanks in advance.

Was it helpful?

Solution

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.

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top