【问题标题】:Rcpp: declare elements (NumericMatrix) of a ListMatrix dynamicallyRcpp:动态声明 ListMatrix 的元素(NumericMatrix)
【发布时间】:2018-07-08 21:59:50
【问题描述】:

我想知道如何动态声明 ListMatrix 的元素(NumericMatrix)。假设我有一个动态维度的 ListMatrix dp1,我想在 Rcpp 中做以下事情:

#include<Rcpp.h>

// [[Rcpp::export]]
Rcpp::ListMatrix ListMatrixType(Rcpp::ListMatrix dp1){

    // Question: how to declare the type of elements of the ListMatrix 
    // dynamically according to the dimension of dp1?
    // I want to avoid the verbose method as below:
    Rcpp::NumericMatrix dp1_00 = dp1(0,0);
    Rcpp::NumericMatrix dp1_01 = dp1(0,1);
    Rcpp::NumericMatrix dp1_10 = dp1(1,0);
    Rcpp::NumericMatrix dp1_11 = dp1(1,1);

    // then doing something on dp1_00, dp1_01, ..., and others
    dp1_00(0,0) = 100;

    // then update dp1
    dp1(0,0) = dp1_00;
    dp1(0,1) = dp1_01;
    dp1(1,0) = dp1_10;
    dp1(1,1) = dp1_11;

    return dp1;
}

例如,dp1 = matrix(rep(list(matrix(1,100,2)),2*2),2,2)。预期输出与dp1 相同。

【问题讨论】:

  • 请在 dp1 中提供一些示例数据以及 R 中的预期输出。
  • 例如,dp1 = matrix(rep(list(matrix(1,100,2)),2*2),2,2)。预期输出与dp1 相同。

标签: r rcpp


【解决方案1】:

关于“动态声明”,我认为目标是避免多次输入NumericMatrix 并且处理不同的数据类型。

如果是这样,嵌套循环就足够了。参考文献

#include<Rcpp.h>

// [[Rcpp::export]]
Rcpp::ListMatrix ListMatrixType_dynamic(Rcpp::ListMatrix x){

    // Dimensions of the List Matrix 
    int n_element_rows = x.nrow();
    int n_element_cols = x.ncol();

    // Loop over each row
    for(int i = 0; i < n_element_rows; ++i) {
        // Loop over each column
        for(int j = 0; j < n_element_cols; ++j) {
            // Retrieve element
            Rcpp::NumericMatrix a = x(i, j);
            // Modify element uniquely by row and column position
            Rcpp::NumericMatrix b = Rcpp::clone(a) + i + j;
            // Store element back into position
            x(i, j) = b; 
        }
    }

    // Return an object back to _R_
    return x;
}

【讨论】:

  • 非常感谢!我们可以避免使用循环吗?因为我必须为 ListMatrix 的每个列表做很多计算。上面的 rcpp 函数将被调用数千次。我注意到有一种类似 R (stackoverflow.com/questions/17973442/…) 的索引方法,但我无法让它在我的计算机上运行。
  • 因此,与 R 相比,C++ 中的循环还不错。如果没有更具体的内容,我会说上述内容非常适合您使用前面讨论的内置“唯一性”内存分配的情况。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-11-09
  • 1970-01-01
  • 2021-06-17
  • 2020-01-09
  • 1970-01-01
相关资源
最近更新 更多