9

假设我List在 Rcpp 中有一个,这里称为x包含矩阵。x[0]我可以使用或其他东西提取其中一个元素。但是,如何提取该矩阵的特定元素?我的第一个想法是,x[0](0,0)但这似乎不起作用。我尝试使用*标志,但也不起作用。

这是一些打印矩阵的示例代码(显示矩阵可以很容易地提取):

library("Rcpp")

cppFunction(
includes = ' 
NumericMatrix RandMat(int nrow, int ncol)
 {
  int N = nrow * ncol;
  NumericMatrix Res(nrow,ncol);
  NumericVector Rands  = runif(N);
   for (int i = 0; i < N; i++) 
  {
    Res[i] = Rands[i];
  }
  return(Res);
 }',

code = '
void foo()
{
  List x;
  x[0] = RandMat(3,3);
  Rf_PrintValue(wrap( x[0] )); // Prints first matrix in list.
}
')


foo()

如何更改Rf_PrintValue(wrap( x[0] ));此处的行以打印第一行和第一列中的元素?在我想使用它的代码中,我需要提取这个元素来进行计算。

4

2 回答 2

9

快速的:

  1. C++ 中的复合表达式有时会很麻烦;模板魔法妨碍了。因此,只需将List对象分配给 a 无论元素是什么,例如 a NumericMatrix

  2. NumericMatrix然后从你认为合适的地方挑选。我们有 row, col, element, ... 访问。

  3. 使用打印可能更容易,Rcpp::Rcout << anElement但请注意,我们目前无法打印整个矩阵或向量——但intordouble类型很好。

编辑:

这是一个示例实现。

#include <Rcpp.h>

// [[Rcpp::export]]
double sacha(Rcpp::List L) {
    double sum = 0;
    for (int i=0; i<L.size(); i++) {
        Rcpp::NumericMatrix M = L[i];
        double topleft = M(0,0);
        sum += topleft;
        Rcpp::Rcout << "Element is " << topleft << std::endl;
    }
    return sum;    
}

/*** R
set.seed(42)
L <- list(matrix(rnorm(9),3), matrix(1:9,3), matrix(sqrt(1:4),2))
sacha(L) # fix typo   
*/

及其结果:

R> Rcpp::sourceCpp('/tmp/sacha.cpp')

R> set.seed(42)

R> L <- list(matrix(rnorm(9),3), matrix(1:9,3), matrix(sqrt(1:4),2))

R> sacha(L)
Element is 1.37096
Element is 1
Element is 1
[1] 3.37096
R>
于 2013-07-31T15:04:28.360 回答
6

你必须在某些时候明确。该类List不知道它包含的元素的类型,它不知道它是一个矩阵列表。

Dirk 向您展示了我们通常做的事情,将元素作为 a 获取NumericMatrix并处理矩阵。

这是一个替代方案,它假设列表中的所有元素都具有相同的结构,使用新的类模板:ListOf使用足够的胶水使用户代码无缝。这只是将明确性转移到不同的地方。

#include <Rcpp.h>
using namespace Rcpp ;

template <typename WHAT>
class ListOf : public List {
public:
    template <typename T>
    ListOf( const T& x) : List(x){}

    WHAT operator[](int i){ return as<WHAT>( ( (List*)this)->operator[]( i) ) ; }

} ;

// [[Rcpp::export]]
double sacha( ListOf<NumericMatrix> x){
    double sum = 0.0 ; 
    for( int i=0; i<x.size(); i++){
        sum += x[i](0,0) ;    
    }
    return sum ;
}

/*** R
    L <- list(matrix(rnorm(9),3), matrix(1:9,3), matrix(sqrt(1:4),2))
    sacha( L )
*/

当我sourceCpp这个文件时,我得到:

> L <- list(matrix(rnorm(9), 3), matrix(1:9, 3), matrix(sqrt(1:4), 2))    
> sacha(L)
[1] 1.087057
于 2013-08-02T10:25:45.530 回答