7

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.

Romain Francois
  • 17,432
  • 3
  • 51
  • 77
xbsd
  • 2,438
  • 4
  • 25
  • 35

2 Answers2

7

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.

Dirk Eddelbuettel
  • 360,940
  • 56
  • 644
  • 725
  • thanks for the feedback. I have been getting a lot of errors on Mavericks ever since upgrading from Mountain Lion and was one of the reasons why I stopped using into Armadillo for the time being. I have posted the error at http://stackoverflow.com/questions/19920281/rcpparmadillo-compile-errors-on-os-x-mavericks using the solution you posted. I have updated Makevars and followed almost every lead on the net to no avail. Should be able to use it once this is solved. – xbsd Nov 12 '13 at 03:23
4

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.

Community
  • 1
  • 1
Kevin Ushey
  • 20,530
  • 5
  • 56
  • 88