首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >二次型在RcppParallel中的并行计算

二次型在RcppParallel中的并行计算
EN

Stack Overflow用户
提问于 2016-11-02 05:31:14
回答 1查看 143关注 0票数 0

我想写一个使用RcppParallel计算v^T Av的代码。这里v是大小为n的向量,A是n乘以n的矩阵。我的想法是以并行的方式计算Av,然后用v计算这个向量的内积。这是我的代码:

代码语言:javascript
运行
复制
#include <Rcpp.h>
// [[Rcpp::depends(RcppParallel)]]
#include <RcppParallel.h>
#include<iostream>
#include<vector>
#include<algorithm>
#include<numeric>

using namespace std;
using namespace Rcpp;
using namespace RcppParallel;

struct Par_MatVec_Mult: public Worker {

  const RMatrix<double> Mat;
  const vector<double> Vec;
  vector<double> output;

  Par_MatVec_Mult(RMatrix<double> A, vector<double> v, vector<double> Av): \ 
  vector<double> Av): Mat(A), Vec(v), output(Av) { }
  void operator() ( size_t begin, size_t end) {

    for( size_t i = begin; i < end; i++ ) {
      RMatrix<double>::Row rowi = Mat.row(i);
       output.at(i) = inner_product( rowi.begin(), rowi.end(),Vec.begin(), \
       0.0 );
    }
  }
};

// [[Rcpp::export]]
double Parallel_MatVec_Mult( NumericMatrix A, vector<double> v ){

  vector<double> b( A.nrow(), 0.0 );
  Par_MatVec_Mult Av(A, v, b);
  parallelFor(0, A.nrow(), Av);
  return inner_product( Av.output.begin(), Av.output.end(), v.begin(), 0.0   );
}

在编译时,我得到了以下错误。

代码语言:javascript
运行
复制
no known conversion for argument 1 from 'Rcpp::NumericMatrix {akaRcpp::Matrix<14>}' 
to 'RcppParallel::RMatrix<double>'

我很清楚NumericMatrix和RMatrix是两个不同的对象。然而,我不知道它们到底有什么不同,我如何才能改变我的代码来摆脱这个错误。

顺便说一下,我在Windows10上使用的是RStudio 0.99.903。

EN

回答 1

Stack Overflow用户

发布于 2016-11-02 06:00:42

RMatrixsingle-argument constructor标记为explicit

代码语言:javascript
运行
复制
inline explicit RMatrix(const Source& source) 
   : data_(const_cast<Source&>(source).begin()),
     nrow_(source.nrow()),
     ncol_(source.ncol())
{}

您已经为Par_MatVec_Mult构造函数提供了此签名

代码语言:javascript
运行
复制
Par_MatVec_Mult(RMatrix<double> A, vector<double> v, vector<double> Av)

并试图稍后向其传递NumericMatrix。这将需要在RMatrix的构造中进行隐式转换,但是由于原本合适的构造函数被标记为explicit,因此这是不允许的,并且您会得到一个错误。

下面是一个简单的示例,演示了这一点:

代码语言:javascript
运行
复制
#include <Rcpp.h>

class Wrapper {
private:
    std::size_t nr;
    std::size_t nc;

public:
    template <typename T>
    explicit Wrapper(const T& t)
        : nr(t.nrow()),
          nc(t.ncol())
    {}

    std::size_t size() const { return nr * nc; }
};

// [[Rcpp::export]]
int test(Rcpp::NumericMatrix x) {
    // Wrapper w = x;   // Error: conversion from ‘Rcpp::NumericMatrix
                        // {aka Rcpp::Matrix<14>}’ to non-scalar
                        // type ‘Wrapper’ requested

    Wrapper w(x);       // Ok

    return w.size();
}

在您的例子中,修复很简单:只需将Par_MatVec_Mult的构造函数的签名更改为:

代码语言:javascript
运行
复制
Par_MatVec_Mult(NumericMatrix A, vector<double> v, vector<double> Av)
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/40368973

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档