我正在使用 Rcpp 来加速一些 R 代码(实际上这是我 2014 年“待办事项”列表中的项目之一),部分代码包括将矩阵列表乘以标量,我能够得到结果,尽管如此,矩阵不再是矩阵,而是向量,我想要一个矩阵列表作为最终输出。
这是我到目前为止的代码:
// [[Rcpp::depends(RcppArmadillo)]]
#include <RcppArmadillo.h>
using namespace Rcpp;
using namespace arma;
// I got this template from here: http://stackoverflow.com/a/18014655/1315767
template <typename WHAT>
class ListOf : public List {
public:
template <typename T>
ListOf( const T& x) : List(x){}
WHAT operator[](int i){ return as<WHAT>( ( (List*)this)->operator[]( i) ) ; }
} ;
// [[Rcpp::export]]
List FooList(NumericVector fi1, ListOf<NumericMatrix> Ct){
List TempList(Ct.size());
NumericMatrix ct(2,2);
for(int i=0; i<Ct.size(); i++){
ct = Ct[i] ;
TempList[i] = ct * fi1[i] ; // multiply each matrix by each scalar in fi1
}
return TempList;
}
运行此代码时,我得到以下信息:
> sourceCpp("FooList.cpp")
> A <- replicate(3,matrix(1:4, 2), simplify=FALSE) # a list of matrices
> vec <- 0.5 * c(1:3) # a vector
> FooList(vec, A) # dim are not preserved
[[1]]
[1] 0.5 1.0 1.5 2.0
[[2]]
[1] 1 2 3 4
[[3]]
[1] 1.5 3.0 4.5 6.0
输出由下式给出FooList
可以,但格式不行,我期望得到这样的结果:
[[1]]
[,1] [,2]
[1,] 0.5 1.5
[2,] 1.0 2.0
[[2]]
[,1] [,2]
[1,] 1 3
[2,] 2 4
[[3]]
[,1] [,2]
[1,] 1.5 4.5
[2,] 3.0 6.0
我不明白为什么我会得到这个输出,因为ct
是一个矩阵,如果我去掉fi1[i]
输出确实是一个矩阵列表,我什至尝试使用as_scalar(fi)
我得到的和以前一样。我也尝试过使用ct.attr("dim") = Dimension(2, 2);
没有成功。