Vectorized log1p() in RcppArmadillo

1725 views c++
2

What is the appropriate way to apply log1p() to an entire arma::vec? It seems that there are vectorized versions of log() and exp(), but not log1p(). I found that there's syntactic sugar for NumericVector, so I end up converting arma::vec to NumericVector, applying log1p(), then converting back:

#include <RcppArmadillo.h>

using namespace Rcpp;

// [[Rcpp::depends(RcppArmadillo)]]

// [[Rcpp::export]]
arma::vec test_log1p( arma::vec v )
{
  // arma::vec res = log1p(v);         // results in a compilation error
  NumericVector v1 = log1p( wrap(v) );
  arma::vec res = as<arma::vec>(v1);
  return res;
}

Is there a more elegant way of doing this?

answered question

1 Answer

6

The devil is, once again, in the detail.

For starters, RcppArmadillo does not have 'Sugar' so your reasoning is flawed--you can't just look at the Rcpp Sugar functions that are working on Rcpp::NumericVector.

Then again, one can convert as you did. But you chose an expensive conversion. Look into the advanced constructors explicitly reusing memory -- no copies needed.

A much simpler and more direct (yet local) approach would just be to add a little local inlined function. That's what I would do :) Done in a few minutes.

Lastly, we have some sibbling projects that generalized Rcpp Sugar over anything that can take iterators. That is "the high road" and it could do with some fresh development. Maybe start at this repo.

posted this

Have an answer?

JD

Please login first before posting an answer.