如何在 R 中编写用于简单矩阵乘法的 Rcpp 函数 [英] How to write Rcpp function for simple matrix multiplication in R

查看:138
本文介绍了如何在 R 中编写用于简单矩阵乘法的 Rcpp 函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写了一个 Rcpp 代码来计算 R 中的元素矩阵乘法.但是当尝试运行此代码时,R 停止工作并退出.如何修正这个功能?

I have wrote a Rcpp code to compute element wise matrix multiplication in R. But when try to run this code R stops working and its exiting. How to correct this function?

提前致谢.

library(Rcpp)
func <- 'NumericMatrix mmult( NumericMatrix m , NumericMatrix v, bool  byrow=true )
{
if( ! m.nrow() == v.nrow() ) stop("Non-conformable arrays") ;
if( ! m.ncol() == v.ncol() ) stop("Non-conformable arrays") ;

NumericMatrix out(m) ;

for (int i = 1; i <= m.nrow(); i++) 
{
  for (int j = 1; j <= m.ncol(); j++) 
    {
      out(i,j)=m(i,j) * v(i,j) ;
    }
}
return out ;
}'

cppFunction( func )

m1<-matrix(1:4,2,2)
m2<-m1
r1<-mmult(m1,m2)
r2<-m1*m2

推荐答案

(至少对我而言)明显的选择是使用 RcppArmadillo:

The (at least to me) obvious choice is to use RcppArmadillo:

R> cppFunction("arma::mat matmult(arma::mat A, arma::mat B) { return A % B; }", 
+              depends="RcppArmadillo")
R> m1 <- m2 <- matrix(1:4,2,2)
R> matmult(m1,m2)
     [,1] [,2]
[1,]    1    9
[2,]    4   16
R> 

因为犰狳是强类型的,并且有一个逐个元素的乘法运算符(%),我们在它需要的单行中使用它.

as Armadillo is strongly typed, and has an element-by-element multiplication operator (%) which we use in the one-liner it takes.

这篇关于如何在 R 中编写用于简单矩阵乘法的 Rcpp 函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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