犰狳-长向量中每个小块的范数 我在C++中使用犰狳。

犰狳-长向量中每个小块的范数 我在C++中使用犰狳。,c++,armadillo,rcpparmadillo,C++,Armadillo,Rcpparmadillo,我有一个包含10个元素的长向量。我想取2个相邻值的每个块的范数2。最后我将有5个值 在R中,我可以将该向量转换为矩阵并使用apply,但我不确定在犰狳中如何实现。感谢您的帮助您只需从向量创建一个矩阵,然后在列中循环即可 #include <RcppArmadillo.h> // [[Rcpp::depends(RcppArmadillo)]] // [[Rcpp::export]] arma::vec foo_Cpp(arma::vec x) { // Note that the

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


在R中,我可以将该向量转换为矩阵并使用apply,但我不确定在犰狳中如何实现。感谢您的帮助

您只需从向量创建一个矩阵,然后在列中循环即可

#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
#包括
//[[Rcpp::depends(RcppArmadillo)]]
//[[Rcpp::导出]]
arma::vec foo_Cpp(arma::vec x){
//注意,x的维数必须能被2整除。
arma::mat X=arma::mat(X.memptr(),2,X.n_elem/2);
arma::uwordn=X.n_cols;
arma::vec范数=arma::vec(n);
对于(arma::uwordi=0;ifoo_R你只需要从向量中创建一个矩阵,然后在列中循环

#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
#包括
//[[Rcpp::depends(RcppArmadillo)]]
//[[Rcpp::导出]]
arma::vec foo_Cpp(arma::vec x){
//注意,x的维数必须能被2整除。
arma::mat X=arma::mat(X.memptr(),2,X.n_elem/2);
arma::uwordn=X.n_cols;
arma::vec范数=arma::vec(n);
对于(arma::uwordi=0;i