C++ 逐行逆数值矩阵
使用C++ 逐行逆数值矩阵,c++,rcpp,C++,Rcpp,使用Rcpp,对于我用R编写的包,我试图反转一个数值矩阵,这样最后一行现在将成为第一行,第一行将成为最后一行,换句话说,相对行索引将从1、2、3、。。。nton,n-1,n-2。。。。1 因此,如果我声明以下函数: NumericMatrix reverseByRow(NumericMatrix in){ int r = in.nrow(); NumericMatrix nw(r,in.ncol()); for(int i = 0; i < r; i++){ nw.ro
Rcpp
,对于我用R编写的包,我试图反转一个数值矩阵,这样最后一行现在将成为第一行,第一行将成为最后一行,换句话说,相对行索引将从1、2、3、。。。n
ton,n-1,n-2。。。。1
因此,如果我声明以下函数:
NumericMatrix reverseByRow(NumericMatrix in){
int r = in.nrow();
NumericMatrix nw(r,in.ncol());
for(int i = 0; i < r; i++){
nw.row(i) = in.row(r-i-1);
}
return nw;
}
我肯定错过了一些非常明显的东西 这是一个“固定”版本,具有合适的变量名:
#include <Rcpp.h>
using namespace Rcpp;
// [[Rcpp::export]]
NumericMatrix reverseByRow(NumericMatrix inmat) {
int r = inmat.nrow();
NumericMatrix nw(r,inmat.ncol());
for(int i = 0; i < r; i++){
nw.row(i) = inmat.row(r-i-1);
}
return nw;
}
/*** R
M <- matrix(1:9, 3, 3)
M
reverseByRow(M)
*/
#包括
使用名称空间Rcpp;
//[[Rcpp::导出]]
NumericMatrix reverseByRow(NumericMatrix inmat){
int r=inmat.nrow();
数值矩阵nw(r,inmat.ncol());
对于(int i=0;i M M
[,1] [,2] [,3]
[1,] 1 4 7
[2,] 2 5 8
[3,] 3 6 9
R> 反向旋转(米)
[,1] [,2] [,3]
[1,] 3 6 9
[2,] 2 5 8
[3,] 1 4 7
R>
您确定这不是巧合吗?整个mid
是什么样子的?当我在这个对象上测试你的函数时(在将中的参数的名称更改为不会导致编译错误的名称后)-矩阵(1:9,nrow=3)
-它工作正常。@nrussell抢先一步。我也在这里工作。
Reversing1: 2806
Reversing2: 7
Reversed1: 2806
Reversed2: 7
#include <Rcpp.h>
using namespace Rcpp;
// [[Rcpp::export]]
NumericMatrix reverseByRow(NumericMatrix inmat) {
int r = inmat.nrow();
NumericMatrix nw(r,inmat.ncol());
for(int i = 0; i < r; i++){
nw.row(i) = inmat.row(r-i-1);
}
return nw;
}
/*** R
M <- matrix(1:9, 3, 3)
M
reverseByRow(M)
*/
R> sourceCpp("/tmp/nicholas.cpp")
R> M <- matrix(1:9, 3, 3)
R> M
[,1] [,2] [,3]
[1,] 1 4 7
[2,] 2 5 8
[3,] 3 6 9
R> reverseByRow(M)
[,1] [,2] [,3]
[1,] 3 6 9
[2,] 2 5 8
[3,] 1 4 7
R>