行列を引数とする関数の例
> library(inline)
> src <- '
+ Rcpp::NumericMatrix xcpp(x);
+ int nrows = xcpp.nrow();
+ int ncolumns = xcpp.ncol();
+ for (int i = 0; i < nrows; i++) {
+ for (int j = 0; j < ncolumns; j++) {
+ xcpp[nrows * j + i] *= 2;
+ }
+ }
+ return xcpp;
+ '
> doublematrix <- cxxfunction(signature(x = "numeric"), body = src, plugin="Rcpp")
> print(doublematrix(matrix(1:10, nrow = 2)))
[,1] [,2] [,3] [,4] [,5]
[1,] 2 6 10 14 18
[2,] 4 8 12 16 20
> src1 <- '
+ Rcpp::NumericMatrix xbem(xbe);
+ int nrows = xbem.nrow();
+ Rcpp::NumericVector gv(g);
+ for (int i = 1; i < nrows; i++) {
+ xbem(i,_) = xbem(i-1,_) * gv[0] + xbem(i,_);
+ }
+ return xbem;
+ '
> funCPP1 <- cxxfunction(signature(xbe = "numeric", g="numeric"), body = src1, plugin="Rcpp")
> A <- matrix(1:12, 3, 4)
> funCPP1(A, 0.5)
[,1] [,2] [,3] [,4]
[1,] 1.00 4.0 7.00 10
[2,] 2.50 7.0 11.50 16
[3,] 4.25 9.5 14.75 20
> src <- '
+ Rcpp::NumericMatrix input(x);
+ int nc = input.ncol();
+ Rcpp::NumericMatrix output = clone<NumericMatrix>(input);
+ for (int i = 1; i < nc; i++) {
+ output.column(i) = output.column(i-1)+input.column(i);
+ }
+ return output;
+ '
> row.cumsum <- cxxfunction(signature(x="numeric"), src, plugin="Rcpp")
> (a <- matrix(1:12, 3, 4))
[,1] [,2] [,3] [,4]
[1,] 1 4 7 10
[2,] 2 5 8 11
[3,] 3 6 9 12
> row.cumsum(a)
[,1] [,2] [,3] [,4]
[1,] 1 5 12 22
[2,] 2 7 15 26
[3,] 3 9 18 30
※コメント投稿者のブログIDはブログ作成者のみに通知されます