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.
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.
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 .
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With