(Rcpp, armadillo) 将 arma::vec 转换为 arma::mat

inm*_*ain 1 r type-conversion rcpp

我有一个矩阵 X,它是由arma::vectorise函数矢量化的。在对转换后的向量 x 进行一些计算之后,我想将其重塑为arma::mat. 我试图.reshape在犰狳中使用函数,但它给了我这个错误。

注册码

// [[Rcpp::export]]
arma::mat vec2mat(arma::vec x, int nrow, int ncol){
  return x.reshape(nrow, ncol);
}
Run Code Online (Sandbox Code Playgroud)

错误信息

no viable conversion from returned value of type 'void' to function return type 'arma::mat' (aka 'Mat<doubld>')
Run Code Online (Sandbox Code Playgroud)

有人能帮我找到处理这个问题的好方法吗?在这种情况下,我不确定应该为函数返回类型使用什么类型。如果您知道将向量转换为矩阵的另一种方法,那么它也很棒:)

提前致谢!

Dir*_*tel 6

您在 Armadillo 文档中忽略了/忽略了细节:reshape()是一个已经存在的矩阵的成员函数,而您试图通过赋值来强制它。编译器告诉你没有 mas。所以听编译器。

工作代码

#include <RcppArmadillo.h>

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

// [[Rcpp::export]]
arma::mat vec2mat(arma::vec x, int nrow, int ncol) {
  arma::mat y(x);
  y.reshape(nrow, ncol);
  return y;
}
Run Code Online (Sandbox Code Playgroud)

演示

> Rcpp::sourceCpp("56606499/answer.cpp")  ## filename I used
> vec2mat(sqrt(1:10), 2, 5)
         [,1]     [,2]     [,3]     [,4]     [,5]
[1,] 1.000000 1.732051 2.236068 2.645751 3.000000
[2,] 1.414214 2.000000 2.449490 2.828427 3.162278
> 
Run Code Online (Sandbox Code Playgroud)