Search code examples
rtype-conversionrcpp

(Rcpp, armadillo) convert arma::vec to arma::mat


I have a matrix X, which is vectorized by arma::vectorise function. After some computation on the converted vector x, I want to reshape it into arma::mat. I tried to use .reshape function in Armadillo, but it gives me this error.

Rcpp code

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

Error message

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

Would anyone help me to find a good way to handle this? I'm not sure what type I should use for function return type in this case. If you know another way to convert vector to matrix, then it would be also great :)

Thanks in advance!


Solution

  • You overlooked / ignored details in the Armadillo documentation: reshape() is a member function of an already existing matrix whereas you try to force it with an assignment. And the compiler tells you no mas. So listen to the compiler.

    Working code

    #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;
    }
    

    Demo

    > 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
    >