0

I have a function which takes a vector as input and outputs a scalar and I want to apply this function to a number of observations. The data is structured in a matrix (rows are the number of observations and columns the variables) and the function is:

// [[Rcpp::export]]
double gaussianweight(arma::vec x, arma::mat H) {
  double c       = std::pow(2 * arma::datum::pi, -0.5 * x.n_rows);
  double s       = std::pow(arma::det(H), -1);
  arma::mat Hinv = arma::inv(H);

  return(c * s * std::exp(-0.5 * arma::dot(Hinv * x, Hinv * x)));
}

to every row vector of a arma::mat X. How would I do that efficiently? A loop that lopps over the rows of X or are there better solutions? I use R for the most time and really got used to avoid loops whenever it is possible. I tried the .each_row() operations but had no luck...

Syd Amerikaner
  • 195
  • 1
  • 8
  • Hi, my instinct is to say look into the rowise function on dplyr, but can you please provide a reprex – Bruno Jun 17 '20 at 10:32
  • the thing is that is that I want (have) to outsource it in c++. It is no problem to use ``apply(X, 2, gaussianweight, H) in base R but since I have a lot of loops, I want to try to improve the speed by outsourcing it to c++ – Syd Amerikaner Jun 17 '20 at 10:39
  • you can maybe do parallel computation if you need even more speed, but I personally don't know if your code can be made to work with a vector o vectors and a vector's – Bruno Jun 17 '20 at 10:46
  • How did you apply each_row? – Lenard Dome Jul 14 '20 at 15:28
  • X.each_row( [](const vec& v ){ gaussianweight(v, H); } ); – Syd Amerikaner Jul 14 '20 at 19:01

0 Answers0