(Rcpp, 犰狳) 将 arma::vec 转换为 arma::mat
(Rcpp, armadillo) convert arma::vec to arma::mat
我有一个矩阵 X,它由 arma::vectorise
函数向量化。在对转换后的向量 x 进行一些计算后,我想将其重塑为 arma::mat
。我试图在 Armadillo 中使用 .reshape
函数,但它给了我这个错误。
Rcpp代码
// [[Rcpp::export]]
arma::mat vec2mat(arma::vec x, int nrow, int ncol){
return x.reshape(nrow, ncol);
}
错误信息
no viable conversion from returned value of type 'void' to function return type 'arma::mat' (aka 'Mat<doubld>')
谁能帮我找到一个好的方法来处理这个问题?在这种情况下,我不确定我应该为 function return 类型使用什么类型。如果你知道另一种将向量转换为矩阵的方法,那也很棒:)
提前致谢!
您忽略/忽略了 Armadillo 文档中的细节:reshape()
是 已经存在的矩阵 的成员函数,而您试图通过赋值强制它。编译器告诉你 no 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;
}
演示
> 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
>
我有一个矩阵 X,它由 arma::vectorise
函数向量化。在对转换后的向量 x 进行一些计算后,我想将其重塑为 arma::mat
。我试图在 Armadillo 中使用 .reshape
函数,但它给了我这个错误。
Rcpp代码
// [[Rcpp::export]]
arma::mat vec2mat(arma::vec x, int nrow, int ncol){
return x.reshape(nrow, ncol);
}
错误信息
no viable conversion from returned value of type 'void' to function return type 'arma::mat' (aka 'Mat<doubld>')
谁能帮我找到一个好的方法来处理这个问题?在这种情况下,我不确定我应该为 function return 类型使用什么类型。如果你知道另一种将向量转换为矩阵的方法,那也很棒:)
提前致谢!
您忽略/忽略了 Armadillo 文档中的细节:reshape()
是 已经存在的矩阵 的成员函数,而您试图通过赋值强制它。编译器告诉你 no 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;
}
演示
> 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
>