Update Rcpp::NumericMatrix passed by reference using RcppArmadillo submat()

后端 未结 1 1083
难免孤独
难免孤独 2021-01-28 08:25

Following on this question, I am trying to understand how to efficiently update a subset of a Rccp::NumericMatrix data type.

I have the following scenario:<

1条回答
  •  不思量自难忘°
    2021-01-28 08:46

    The left side of your assignment in updateMatrix creates a temporary that is discarded after assignment. Therefore, m doesn't change at all. The code can't work as you expected as the that would mean the type of m would change. Look below:

    #include 
    #include 
    #include 
    // [[Rcpp::depends(RcppArmadillo)]]
    
    
    // [[Rcpp::export]]
    void updateMatrix(const Rcpp::NumericMatrix &m)
    {
      std::cout << m << std::endl;
    
      std::cout << typeid(m).name() << std::endl;
    
      arma::mat m2 = Rcpp::as(m);
    
      std::cout << typeid(m2).name() << std::endl;
    
      m2.submat(0, 0, 3, 3) = Rcpp::as(m).submat(0, 0, 3, 3) + 1;
    
      std::cout << m2 << std::endl;
    }
    

    Running this code gives:

    > m = matrix(0, 5, 5)
    > updateMatrix(m)
    0.00000 0.00000 0.00000 0.00000 0.00000
    0.00000 0.00000 0.00000 0.00000 0.00000
    0.00000 0.00000 0.00000 0.00000 0.00000
    0.00000 0.00000 0.00000 0.00000 0.00000
    0.00000 0.00000 0.00000 0.00000 0.00000
    
    N4Rcpp6MatrixILi14ENS_15PreserveStorageEEE
    N4arma3MatIdEE
       1.0000   1.0000   1.0000   1.0000        0
       1.0000   1.0000   1.0000   1.0000        0
       1.0000   1.0000   1.0000   1.0000        0
       1.0000   1.0000   1.0000   1.0000        0
            0        0        0        0        0
    

    0 讨论(0)
提交回复
热议问题