Reputation: 101
I would like to know how to declare elements (NumericMatrix) of a ListMatrix dynamically. Suppose I have a ListMatrix dp1
with dynamic dimension, I want to do the following things in 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;
}
For example, dp1
= matrix(rep(list(matrix(1,100,2)),2*2),2,2). Expected output is same with dp1
.
Upvotes: 1
Views: 389
Reputation: 20746
Regarding "dynamic declaration", I think the goal is to avoid typing out NumericMatrix
multiple times and not handling different data types.
If that's the case, a nested loop will suffice. c.f.
#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;
}
Upvotes: 1