0

我使用包定义了两个函数RcppArmadillo并将它们保存到文件cxxFuns.cpp中。f01和之间的唯一区别f02是 的位置V(0, 0)

#include <RcppArmadillo.h>
using namespace Rcpp;

// [[Rcpp::export]]
arma::mat f01 (arma::mat x) {
    unsigned int p0 = x.n_cols ;
    unsigned int iR = 0, iC = 0 ;
    arma::mat V(3, 3) ; V.fill(NA_REAL) ;
    for (iR = 0; iR < p0; iR++) { 
        V(0, 0) = arma::sum(x.col(iR) % x.col(iR)) ;
        for (iC = iR+1; iC < p0; iC++) {
            ;
        }
    }
    
    return V ;
}

// [[Rcpp::export]]
arma::mat f02 (arma::mat x) {
    unsigned int p0 = x.n_cols ;
    unsigned int iR = 0, iC = 0 ;
    arma::mat V(3, 3) ; V.fill(NA_REAL) ;
    for (iR = 0; iR < p0; iR++) { 
        for (iC = iR+1; iC < p0; iC++) {
            V(0, 0) = arma::sum(x.col(iR) % x.col(iR)) ;
        }
    }
    
    return V ;
}

据我了解,该功能f01应该f02给出相同的结果。然而,测试并没有显示出预期的结果。

rm(list=ls())
set.seed(2020)
Rcpp::sourceCpp('cxxFuns.cpp')
x <- matrix(rnorm(100*10), 10)
(egg01 <- f01(x))
         [,1] [,2] [,3]
[1,] 12.78607   NA   NA
[2,]       NA   NA   NA
[3,]       NA   NA   NA

(egg02 <- f02(x))
         [,1] [,2] [,3]
[1,] 14.80855   NA   NA
[2,]       NA   NA   NA
[3,]       NA   NA   NA

发生了什么?

4

1 回答 1

3

第一个块中的最后一次执行是 when iR = p0-1

第二个块中的最后一次执行是 when iC=p0-1
由于iC开始为iR+1,您的最后一次执行是 for iR=p0-2

iR在计算或在调试器下运行之前打印值V(0,0)应该立即清楚地说明这一点。

于 2020-10-29T15:45:19.607 回答