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
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.
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.