Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Element-Wise Matrix Multiplication in Rcpp

Tags:

rcpp

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.

like image 400
xbsd Avatar asked Nov 11 '13 22:11

xbsd


People also ask

How do you multiply matrices with element wise?

The elementwise multiplication operator (#) computes a new matrix with elements that are the products of the corresponding elements of matrix1 and matrix2. In addition to multiplying matrices that have the same dimensions, you can use the elementwise multiplication operator to multiply a matrix and a scalar.

What is element by element multiplication in matrix?

Element-By-Element Multiplication (Vectorize) This will tell Mathcad to ignore the normal matrix rules and perform the operation on each element. To vectorize the multiplication operation, select the entire expression, and then type .


1 Answers

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.

like image 148
Dirk Eddelbuettel Avatar answered Sep 30 '22 13:09

Dirk Eddelbuettel