2016-04-25 60 views
3

我想採取arma::vec對象並將其重塑爲arma::cube對象。犰狳從矢量向立方體重塑

例如:

vec param(mm*n*g); 
param.randn(); 
cube LL = reshape(param,mm,n,g); // this line doesn't work 

我能得到這個工作,最簡單的方法是:

paramtemp = as<NumericVector>(wrap(param)); 
cube LL(paramtemp.begin(),mm,n,g); 

但肯定有更優雅的方式?

回答

2

許多Armadillo類提供的構造函數採用的參數是指向另一個內存位置的指針;通常這將是另一個對象的迭代器begin。例如,

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

// [[Rcpp::export]] 
arma::cube to_cube(int x, int y, int z) { 
    arma::vec v(x * y * z); 
    v.randn(); 

    arma::cube res((const double*)v.begin(), x, y, z); 
    return res; 
} 

/***R 

to_cube(3, 3, 3) 
# , , 1 
# 
#   [,1]  [,2]  [,3] 
# [1,] -0.8052190 0.5206867 0.4562287 
# [2,] 0.6407149 0.8247035 -0.2375103 
# [3,] -0.2766542 0.0527188 -1.2807390 
# 
# , , 2 
# 
#    [,1]  [,2]  [,3] 
# [1,] -0.49995982 0.7240956 0.66634699 
# [2,] 0.06367092 -0.7991327 -0.36003560 
# [3,] -0.90958952 -0.4431064 0.05952237 
# 
# , , 3 
# 
#   [,1]  [,2]  [,3] 
# [1,] 0.457159 1.6725911 -0.9299367 
# [2,] 1.205733 0.6185083 0.3805266 
# [3,] 0.545668 -0.4356577 -0.9111175 

*/ 

我不知道如果轉換到const double*是絕對必要的,但它是有以下兩個構造來區分,

  • cube(const ptr_aux_mem, n_rows, n_cols, n_slices)
  • cube(ptr_aux_mem, n_rows, n_cols, n_slices, copy_aux_mem = true, strict = false)

其中第一個(這是以上意圖)是隻讀副本。