Element-Wise Matrix Multiplication in Rcpp

前提是你 提交于 2019-12-28 04:25:25

问题


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.


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/19917023/element-wise-matrix-multiplication-in-rcpp

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!