【问题标题】:Matrix Multiplication Using NumericMatrix and NumericVector in Rcpp在 Rcpp 中使用 NumericMatrix 和 NumericVector 进行矩阵乘法
【发布时间】:2015-04-12 11:56:54
【问题描述】:

我想知道有没有一种使用 NumericMatrix 和 NumericVector 类计算矩阵乘法的方法。我想知道是否有任何简单的方法 帮助我避免以下循环进行此计算。我只想计算 X%*%beta。

// assume X and beta are initialized and X is of dimension (nsites, p), 
// beta is a NumericVector with p elements. 
for(int j = 0; j < nsites; j++)
 {
    temp = 0;

    for(int l = 0; l < p; l++) temp = temp + X(j,l) * beta[l];

}

提前非常感谢您!

【问题讨论】:

  • 我会调查 RcppArmadillo 或 RcppEigen。
  • 我明白了,只是为了确认,Rcpp 糖没有 %*% 像 R,对吧?非常感谢您的帮助!

标签: matrix-multiplication rcpp


【解决方案1】:

根据 Dirk 的评论,这里有几个案例通过重载的 * 运算符演示了 Armadillo 库的矩阵乘法:

#include <RcppArmadillo.h>
// [[Rcpp::depends(RcppArmadillo)]]

// [[Rcpp::export(".mm")]]
arma::mat mm_mult(const arma::mat& lhs,
                  const arma::mat& rhs)
{
  return lhs * rhs;
}

// [[Rcpp::export(".vm")]]
arma::mat vm_mult(const arma::vec& lhs,
                  const arma::mat& rhs)
{
  return lhs.t() * rhs;
}

// [[Rcpp::export(".mv")]]
arma::mat mv_mult(const arma::mat& lhs,
                  const arma::vec& rhs)
{
  return lhs * rhs;
}

// [[Rcpp::export(".vv")]]
arma::mat vv_mult(const arma::vec& lhs,
                  const arma::vec& rhs)
{
  return lhs.t() * rhs;
}

然后您可以定义一个 R 函数来调度适当的 C++ 函数:

`%a*%` <- function(x,y) {

  if (is.matrix(x) && is.matrix(y)) {
    return(.mm(x,y))
  } else if (!is.matrix(x) && is.matrix(y)) {
    return(.vm(x,y))
  } else if (is.matrix(x) && !is.matrix(y)) {
    return(.mv(x,y))
  } else {
    return(.vv(x,y))
  }

}
##
mx <- matrix(1,nrow=3,ncol=3)
vx <- rep(1,3)
my <- matrix(.5,nrow=3,ncol=3)
vy <- rep(.5,3)

与 R 的 %*% 函数相比:

R>  mx %a*% my
     [,1] [,2] [,3]
[1,]  1.5  1.5  1.5
[2,]  1.5  1.5  1.5
[3,]  1.5  1.5  1.5

R>  mx %*% my
     [,1] [,2] [,3]
[1,]  1.5  1.5  1.5
[2,]  1.5  1.5  1.5
[3,]  1.5  1.5  1.5
##
R>  vx %a*% my
     [,1] [,2] [,3]
[1,]  1.5  1.5  1.5

R>  vx %*% my
     [,1] [,2] [,3]
[1,]  1.5  1.5  1.5
##
R>  mx %a*% vy
     [,1]
[1,]  1.5
[2,]  1.5
[3,]  1.5

R>  mx %*% vy
     [,1]
[1,]  1.5
[2,]  1.5
[3,]  1.5
##
R>  vx %a*% vy
     [,1]
[1,]  1.5

R>  vx %*% vy
     [,1]
[1,]  1.5

【讨论】:

  • 非常感谢!这个演示对像我这样的初学者非常有帮助和清晰!非常感谢您的帮助!
  • 为什么要使用const
  • 因为没有修改参数的意图。路过const&amp; 是一种常见的习惯用法,请参阅herehere 等任意数量的讨论。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-05-30
  • 1970-01-01
  • 1970-01-01
  • 2013-01-30
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多