I am new to Eigen C++ programming. I am trying to create an Rcpp function to call from R. The function takes a list of matrices (Xlst), and two lists of vectors (ylst and smwlst). In each for-loop iteration, the function should perform standardization of the columns of a matrix and then multiply with the corresponding vectors. Please see the code below.

It appears that I am not initializing the parameters correctly, or I should initialize the parameters outside of the for-loop, which I don't know how to do because the number of rows are not the same for all matrices. Could anyone help with this?

Rcpp function:

List solveR_obj_rLog2_cov(List ylst,
                          List Xlst,
                          List smwlst,
                          int P,
                          int H)
int P, H, h, j, it=0;

Eigen::MatrixXd BetaH = Eigen::MatrixXd::Zero(H, P); 

for(h = 0; h <= H; ++h)
      Eigen::VectorXd yh = ylst[h];
      Eigen::VectorXd lamh = smwlst[h];
      Eigen::MatrixXd Xh = Xlst[h];

      Nh = yh.size();

      double numh, dnmh;
      Eigen::VectorXd yhc(Nh), Xhm(P), Xhsd(P);
      Eigen::MatrixXd Xhs(Nh,P);

      yhm = yh.mean();
      yhc = yh.array() - yhm;

      for(j = 0; j < P; ++j)
        Xhm(j) = Xh.col(j).mean();
        Xh.col(j) = Xh.col(j).array() - Xhm(j);
        Xhsd(j) = sqrt(Xh.col(j).squaredNorm()/Nh);
        Xhs.col(j) = Xh.col(j)/Xhsd(j);

      for(j = 0; j < P; ++j)
        numh = (lamh*yhc.dot(Xhs.col(j))).sum()/Nh;
        dnmh = (lamh*Xhs.col(j).dot(Xhs.col(j))).sum()/Nh;
        BetaH.coeffRef(h,j) = numh/dnmh;
return BetaH;

Data from the R:

yl <- list(allData20$y, allData21$y, allData22$y)
smwl <- list(allData20$w, allData21$w, allData22$w)
Xl <- list(as.matrix(allData20[,2:5]), 

Application in the R:

    c_res <- solveR_obj_rLog2_cov(ylst = yl,
                             Xlst = Xl,
                             smwlst = smwl,
                             P = 4,
                             H = 3)
  • $\begingroup$ You are overwriting the parameters P,H with local variables with undefined value. $\endgroup$ Jul 2 at 21:06

1 Answer 1


You used Eigen::MatrixXd::Zero for initialising BetaH. Why not follow the same for initialising the variables inside the loop?

  • $\begingroup$ Thanks this works $\endgroup$
    – Shakil
    Jul 3 at 3:48

Not the answer you're looking for? Browse other questions tagged or ask your own question.