【问题标题】:(Rcpp, armadillo) convert arma::vec to arma::mat(Rcpp, armadillo) 将 arma::vec 转换为 arma::mat
【发布时间】:2019-06-15 00:46:15
【问题描述】:

我有一个矩阵 X,它由 arma::vectorise 函数向量化。在对转换后的向量 x 进行一些计算之后,我想将其重塑为 arma::mat。我尝试在犰狳中使用.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>')

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

提前致谢!

【问题讨论】:

  • 不使用.reshape()成员函数(前面有一个点),而是使用单机版:reshape()。不需要使用上面的 vec2mat() 函数。

标签: r type-conversion rcpp


【解决方案1】:

您忽略/忽略了犰狳文档中的细节: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
> 

【讨论】:

  • 谢谢你,德克。抱歉,我没有这方面的经验。
  • 有一种更简单、更高效的方法。使用独立的reshape() 函数。示例:mat y = reshape(x, nrow, ncol);
  • 我没有看到带矢量的。
  • @hbrerkere 谢谢,但正如 Dirk 所解释的(在 this documentation 中),它似乎不需要向量。
  • A vector 仍然是一个矩阵,只是一个受限矩阵(一行或一列)。独立的 reshape() 函数似乎适用于任何矩阵,包括向量。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-02-09
  • 2023-03-04
  • 1970-01-01
  • 1970-01-01
  • 2015-01-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多