犰狳-长向量中每个小块的范数

时间:2019-03-04 01:19:59

标签: c++ armadillo rcpparmadillo

我在C ++中使用Armadillo。

我有一个包含10个元素的长向量。我想取2个相邻值的每个块的范数2。最后,我将有5个值。

在R中,我可以将向量转换为矩阵并使用apply,但是我不确定如何在Armadillo中进行操作。感谢任何帮助

1 个答案:

答案 0 :(得分:0)

您只需要从向量创建一个矩阵,然后遍历各列即可。

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


// [[Rcpp::export]]
arma::vec foo_Cpp(arma::vec x) {
// Note that the dimension of x must be divisible by two.
  arma::mat X = arma::mat(x.memptr(), 2, x.n_elem/2);
  arma::uword n = X.n_cols;
  arma::vec norms = arma::vec(n);
  for (arma::uword i = 0; i < n; i++) {
    norms(i) = arma::norm(X.col(i), 2);
  }
  return norms;
}



/*** R
foo_R <- function(x) {
  X <- matrix(x, 2, length(x)/2)
  apply(X, 2, norm, type = "2")
}
x <- rnorm(1000)
all.equal(foo_R(x), c(foo_Cpp(x)))
microbenchmark::microbenchmark(foo_R(x), foo_Cpp(x))
*/

> all.equal(foo_R(x), c(foo_Cpp(x)))
[1] TRUE

> microbenchmark::microbenchmark(foo_R(x), foo_Cpp(x))
Unit: microseconds
       expr       min       lq        mean     median        uq       max neval
   foo_R(x) 17907.290 19640.24 21548.06789 20386.5815 21212.609 50780.584   100
 foo_Cpp(x)     5.133     6.34    26.48266    19.4705    21.734  1191.124   100