Search code examples
c++rrcpprcpparmadillo

Why do the two functions give different results?


I defined two functions using RcppArmadillo package and save them into the file cxxFuns.cpp. The only difference between f01 and f02 is the positions of 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 ;
}

As I understand, the function f01 and f02 should give identical results. However, the testing does not show the expected results.

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

What happened?


Solution

  • The last execution in the first block is when iR = p0-1.

    The last execution in the second block is when iC=p0-1.
    Since iC starts as iR+1, your last execution is for iR=p0-2.

    Printing the value of iR before computing V(0,0) or running under a debugger should have immediately made this clear.