2
我想在R中为big.matrix对象实现一些基本的C++代码。我正在使用Rcpp包,已经阅读演示here,甚至应用了另一个简单函数,我在rcpp-devel list :R Rcpp big.matrix加入
#include "bigmemory/BigMatrix.h"
#include "bigmemory/MatrixAccessor.hpp"
#include <Rcpp.h>
using namespace Rcpp;
// [[Rcpp::export]]
void fun(SEXP A) {
Rcpp::XPtr<BigMatrix> bigMat(A);
MatrixAccessor<int> Am(*bigMat);
int nrows = bigMat->nrow();
int ncolumns = bigMat->ncol();
for (int j = 0; j < ncolumns; j++){
for (int i = 1; i < nrows; i++){
Am[j][i] = Am[j][i] + Am[j][i-1];
}
}
return;
}
// [[Rcpp::export]]
void BigTranspose(SEXP A)
{
Rcpp::XPtr<BigMatrix> pMat(A);
MatrixAccessor<int> mat(*pMat);
int r = pMat->nrow();
int c = pMat->ncol();
for(int i=0; i<r; ++i)
for(int j=0; j<c; ++j)
std::swap(mat[j][i], mat[i][j]);
return;
}
这fun
功能工作完全正常,修改big.matrix对象。
a <- matrix(seq(25), 5,5)
> a
[,1] [,2] [,3] [,4] [,5]
[1,] 1 6 11 16 21
[2,] 2 7 12 17 22
[3,] 3 8 13 18 23
[4,] 4 9 14 19 24
[5,] 5 10 15 20 25
> fun([email protected])
> head(b)
[,1] [,2] [,3] [,4] [,5]
[1,] 1 6 11 16 21
[2,] 3 13 23 33 43
[3,] 6 21 36 51 66
[4,] 10 30 50 70 90
[5,] 15 40 65 90 115
但是,当我尝试一个简单的矩阵矩阵转置函数矩阵不被修改。为什么fun
函数可以工作,但不是我的'BigTranspose`?
a <- matrix(seq(25), 5,5)
> a
[,1] [,2] [,3] [,4] [,5]
[1,] 1 6 11 16 21
[2,] 2 7 12 17 22
[3,] 3 8 13 18 23
[4,] 4 9 14 19 24
[5,] 5 10 15 20 25
b <- as.big.matrix(a)
BigTranspose([email protected])
> head(b)
[,1] [,2] [,3] [,4] [,5]
[1,] 1 6 11 16 21
[2,] 2 7 12 17 22
[3,] 3 8 13 18 23
[4,] 4 9 14 19 24
[5,] 5 10 15 20 25
果然,这是一个简单的疏忽。谢谢你,你也是正确的,任何尺寸都需要进一步编码。 – cdeterman 2014-10-30 18:46:45