Rcpp 中的逐元素矩阵乘法 [英] Element-Wise Matrix Multiplication in Rcpp

查看:44
本文介绍了Rcpp 中的逐元素矩阵乘法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写需要逐元素矩阵乘法的代码.我试图在 Rcpp 中实现这一点,因为代码需要一些昂贵的循环.我对 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).

提前致谢.

推荐答案

您可能希望使用 RcppArmadillo(或 RcppEigen)进行矩阵的实际数学运算.

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> 

按元素乘法也称为 Schur(或 Hadamard)乘法.在犰狳中,% 支持它;有关更多信息,请参阅 Armadillo 文档.

Element-wise multiplication is also called Schur (or Hadamard) multiplication. In Armadillo, the % supports it; see the Armadillo docs for more.

这篇关于Rcpp 中的逐元素矩阵乘法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆