rcpp - 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
这是正确的答案,但无论如何我都有警告。
解决方案
我无法重现这一点。我懂了
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)
*/
如果您需要有关错误或警告的帮助,那么拥有最少完整的可验证示例会有所帮助。
这个问题仍然没有通过测试。
推荐阅读
- multithreading - 在 Delphi 中使用匿名线程来闪烁标签
- list - 在压缩它们之前,如何从包含两个列表的元组中提取两个列表?(使用 OCaml)
- c# - 在运行时选择引用的二进制文件
- php - PHP - 为什么通过引用传递使用相同数量的内存?
- excel - 使用 LEFT() 函数时包括前导零
- ios - iOS tableView 在单击、滚动或切换标签栏项目之前不会重新加载
- javascript - JavaScript:如何一次遍历一列并将子级设置为最大兄弟的宽度,然后再在下一列中重复?
- python - 使用 sklearn 和 gRPC 进行模型服务
- unix-timestamp - 在 Pine Script 中,您如何每天做一次某事,或者跟踪当天是否已完成某事?
- regex - 我可以使用单个正则表达式将键值对解析为命名捕获组吗?