[Rcpp-devel] Connection between arma and rcpp

Honglang Wang wanghonglang2008 at gmail.com
Tue Jan 29 20:20:27 CET 2013


Thanks, I am sorry I did not make my point clear. Let me describe it
clearly:
1) The first question is about using "apply":

// [[Rcpp::depends(RcppArmadillo)]]
#include <RcppArmadillo.h>
using namespace Rcpp;

// [[Rcpp::export]]
List foo(NumericVector x, double h) {
  double r = 0.0;
  for (int i=0; i<100; i++)
    r += i;
  r=r+h;
  return List::create(Named("Sum") = r,
                            Named("h")=h);
}

## For this function, I use two inputs in order to illustrate the problem
for calling this function by using apply.

// [[Rcpp::export]]
double fpp(Function f, NumericMatrix Ar, double h) {
  int n = Ar.nrow(), m = Ar.ncol();
  arma::mat A(Ar.begin(),n,m,false);
  A.reshape(m,n);
  arma::mat U(m,1)=f(A,1, function(x) foo(x, h=h)$Sum);
  double r = arma::accu(U);
  return r;
}

## what is the correct format to using f=apply here? exactly the same as in
R?  The error here is "x" is out of scope.

A <- matrix(rnorm(8),nrow=4)
fpp(apply, A, 3)

2) The second question is if i replace using apply by using for loop, how
to transfer between arma objects and Rcpp objects:

// [[Rcpp::depends(RcppArmadillo)]]
#include <RcppArmadillo.h>
using namespace Rcpp;

// [[Rcpp::export]]
double foo(NumericVector x) {
  double r = 0.0;
  for (int i=0; i<100; i++)
    r += i;
  return r;
}

// [[Rcpp::export]]
double fpp(NumericMatrix Ar) {
  int n = Ar.nrow(), m = Ar.ncol();
  arma::mat A(Ar.begin(),n,m,false);
  A.reshape(m,n);
  arma::mat U(m,1);
  for(int a=0; a<m; a++){
  U(a,1)=foo(as<NumericVector>(A.row(a)));
  }
  double r = arma::accu(U);
  return r;
}

### how to deal with the arma object A.row(a) for the input of foo, which
need rcpp object?

A <- matrix(rnorm(8),nrow=4)
fpp(mean,A)

Thanks.

Best wishes!

Honglang Wang

Office C402 Wells Hall
Department of Statistics and Probability
Michigan State University
1579 I Spartan Village, East Lansing, MI 48823
wangho16 at msu.edu
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.r-forge.r-project.org/pipermail/rcpp-devel/attachments/20130129/4b673d50/attachment-0001.html>


More information about the Rcpp-devel mailing list