首页 > 解决方案 > Rcpp 中的数值矩阵

问题描述

在此处输入图像描述我正在 Rstudio 中编写代码,它在 Rcpp 中使用 NumericVector 和 NumericMatrix。我对 NumericVectors 没有任何问题,但是当我想构造或调用 NumericMatrix 时,我会收到警告(如下例所示)。我的代码工作正常,但由于我不明白警告的原因,我担心它以后可能会在我没有意识到的情况下导致一些问题。如果有人帮助我理解这些警告的含义以及我做错了什么,我将不胜感激。

//[[Rcpp::plugins(cpp11)]]
#include <Rcpp.h>
#include <string>
#include <iostream>
using namespace Rcpp;
using namespace std;

// [[Rcpp::export]]
int sim( const NumericVector v1,
     const NumericMatrix m1)
{
  double a = v1[1];     // no warning
  double b = m1(1,1);   // no matching for call to object of type 'const NumericVector' (aka 'const Matrix<14>')
  NumericMatrix c;
  c = NumericMatrix(10,20);    //no matching constructor for initialization of 'NumericMatrix' (aka 'const Matrix<14>')

  std::cout<<"a= "<<a<<", b= "<<b<<", c(1,1)= "<<c(1,1)<<std::endl;
  return 0;
}

要运行此代码,请获取 sim.cpp,定义 v1 和 v2,然后调用 sim。

library(Rcpp)
v1 <- c(1,2,3)
m1 <- matrix(c(11,22,33,44,55,66),nrow = 2)
sourceCpp("sim.cpp")
sim(v1,m1)

你会看到

[1]a= 2, b= 44, c(1,1)= 0

这是正确的答案,但无论如何我都有警告。

标签: rcpp

解决方案


我无法重现这一点。我懂了

R> library(Rcpp)
R> sourceCpp("~/tmp/so52632570.cpp")

R> v1 <- c(1,2,3)

R> m1 <- matrix(c(11,22,33,44,55,66),nrow = 2)

R> sim(v1,m1)
a= 2, b= 44, c(1,1)= 0
[1] 0
R>

使用此清理后的较小版本的代码:

#include <Rcpp.h>
using namespace Rcpp;

// [[Rcpp::export]]
int sim( const NumericVector v1, const NumericMatrix m1) {
  double a = v1[1];   
  double b = m1(1,1); 
  NumericMatrix c = NumericMatrix(10,20); 
  std::cout<<"a= "<<a<<", b= "<<b<<", c(1,1)= "<<c(1,1)<<std::endl;
  return 0;
}

/*** R
v1 <- c(1,2,3)
m1 <- matrix(c(11,22,33,44,55,66),nrow = 2)
sim(v1,m1)
*/

如果您需要有关错误或警告的帮助,那么拥有最少完整的可验证示例会有所帮助。

这个问题仍然没有通过测试。


推荐阅读