我对 Rcpp 很陌生,我想在 Rcpp 中操作一个矩阵。我在 R 中有一个 3D 矩阵,我想将其转移到 Rcpp 中的函数。我好像做不到!
include <Rcpp.h>
using namespace Rcpp;
// [[Rcpp::export]]
NumericMatrix plusfive(NumericMatrix v) {
int cols = v.cols();
int rows = v.rows();
for(int i = 0; i < rows; i++)
{
for(int j = 0; j < cols; j++)
{
v[i][j] = v[i][j] + 5;
}
}
return(v);
}
/*** R
plusfive()
*/
我收到错误 - 数组下标的类型 'Rcpp::traits::storage_type<14>::type {aka double}[int]' 无效
your text
欢迎来到 StackOverflow! 现在,矩阵“通过设计/通过构造”始终是二维的。在内部,它们被表示为单个向量,其维度属性长度为二——仅强制执行行和列。 所以“三维矩阵”不可能存在,这意味着你不能使用
NumericalMatrix
。
但是无论您想使用哪个维度,都支持数组对象,包括三个。 包中有一些示例,即这是根据其中一项测试改编的
Rcpp::cppFunction("IntegerVector ex() { return IntegerVector( Dimension( 2, 3, 4) ); }")
但是您可能真正想要的是查看 RcppArmadillo 及其
cube
类,它对开箱即用的三维数组有(方式)更多支持。